Chapter 3: Lists, Tuples, Dictionaries and Sets

Ace your homework & exams now with Quizwiz!

Changing and item by offsetting? Syntax

To change a list item we offset before the assignment statement. EX: >>> marxes = ['Groucho', 'Chico', 'Harpo'] >>> marxes[2] = 'Wanda' >>> marxes ['Groucho', 'Chico', 'Wanda']

Set

A Set is like a dictionary excpet the values are discarded at the end of runtime. However the Keys are kept and must be unique.

Defining multiple elements in a tuple?

>>> marx_tuple = 'Groucho', 'Chico', 'Harpo' >>> marx_tuple ('Groucho', 'Chico', 'Harpo')

Using the (in) key to check for if key exists

Syntax: some_dict = {'chap' : 'Gram'} x = 'chap' in some_dict print(x) >>> True

How would you extract multiple elements within a list?

Syntax: var = [some list] var1 = [0:2] You would use the slice operation

Do lists need to be unique?

No, Lists can be repetitive or unique or have order to it.

Are tuples mutable?

No, tuples are immutable 'lists'

set function ()

Can be used to create or tunr list ect into sets. Note: using the set function will discard repeating values. Syntax: set("letters") >>> {l, e, t, r,s}

Methods of copying a list into another variable. Why would you copy a list into another variable through these methods rather than using a assignment (=) statement.

Choices: 1. Use the copy(0 function 2. Use the List(0 conversion function 3. Use the slice [:] list method. >>> a = [1, 2, 3] >>> b = a.copy() >>> c = list(a) >>> d = a[:] These will create copies and are identical but not equivalent. However an Assignment: a = b will refer to the same object and value and any changes made to a will be reflected in b.

Tuple elements are separated by?

Commas , , ,

List syntax

Comprised of zero or more elements assigned within a bracket and separated by commas. var = [values]

clear()

Delete all items in a dict by using clear. Syntax: some_dict.clear()

Dictionaries and their use?

Dictionaries are similar to lists but are unordered. They do not have index offsets but instead use key-pairs to extract the element.

If you provide a list with negative numbers what does it do?

If you are printing a list [-1] as argument then it will print starting at the end of the list until range is met.

How to sort() in reverse

In order to change the sorting method to Descending we have to apply the following: >>> numbers = [2, 1, 4.0, 3] >>> numbers.sort(reverse=True) >>> numbers [4.0, 3, 2, 1]

Important Observation (Get Checked)

It seems that in python FUNCTIONS do not need to be assigned into a variable to produce a change into another variable. However METHODS must be assigned to separate variable in order for data to be stored as changed. Methods do not change the original variable but a copy must be made.

How do lists extraction values differ than from strings?

Lists when provided [0] consider the whole string or character as 0 value where was strings go character by character. Ex: Ghoul -----> 0 for lists Ghoul 0 1 2 3 4 for strings.

What if when copying dict together with update() there are copies of key words?

Python will replace the key-value pair with the one from the second dictionary.

= and copy()

Same assignment and copy function exists in tuples.

split method? What does it do and how?

The split method is attached to a variable and can be given a delimiter or argument to split the sentence by into a list. Default: White Space. Syntax: bday = 08/30/1996 bday_split = bday.split("/") >>> [1,6,1952]

Lists are good for?

They are good for keeping track of things by order. You can change a list and add new elements or replace existing elements or repeat values.

Sets and Dictionaries ?

They can both be made using curly braces{} however a empty curly brace will return a dictionary.

Should you or should you not put () in a tuple?

You can put () when making a tuple but it doesn't seem to be necessary.

del function

You can use the del function to delete a key-value pair in a dict. x = {} del x[key]

Syntax of Dictionaries

You create a dictionary with {} empty_dict = {key : value}

using tuple() to convert other items into tuples.

marx_list = ['Groucho', 'Chico', 'Harpo'] var1 = tuple(marx_list) print(var1) Syntax: var = tuple(argument) the argument usually is the variable for the list or string sequence. A variable needs to be assigned or else it wont retain the change when printed.

.join and .split methods show in contrast

might help to remember: join() is the opposite of split(), as demonstrated here: >>> friends = ['Harry', 'Hermione', 'Ron'] >>> separator = ' * ' >>> joined = separator.join(friends) >>> joined 'Harry * Hermione * Ron' >>> separated = joined.split(separator) >>> separated ['Harry', 'Hermione', 'Ron'] >>> separated == friends True

set()

to create a set you can use the set function or {} curly braces with comma separations. >>> empty_set = set() >>> empty_set set() >>> even_numbers = {0, 2, 4, 6, 8} >>> even_numbers {0, 8, 2, 4, 6} >>> odd_numbers = {1, 3, 5, 7, 9} >>> odd_numbers {9, 3, 1, 5, 7}

get() function

Syntax: x = some_dict.get(Key, Optional Value) You can specify they key with a optional value. If the key exist it will return the value, otherwise it will fill in the optional value.

Defining a Tuple of one element?

Syntax: >>> one_marx = 'Groucho', >>> one_marx ('Groucho',) Note: The Comma after the element.

Syntax of Tuple

Syntax: (Defining): Var_tuple = () > This would return a empty tuple and is similar to creating a empty list.

In operator and its use?

The (in) operator is used in python to check a list to check whether it exists. It is a Boolean statement that returns True or False. Syntax: >>> marxes = ['Groucho', 'Chico', 'Harpo', 'Zeppo'] >>> 'Groucho' in marxes True >>> 'Bob' in marxes False

.join method and its use with strings, lists and tuples.

The .join(Listname..ect) method is used to combine or append a string or any iterable string type (List) to any argument provided.

.index() operator and its function?

The index() operator is commonly used to return the Value of a offset. Syntax: >>> marxes = ['Groucho', 'Chico', 'Harpo', 'Zeppo'] >>> marxes.index('Chico') 1

Extract an item from a list by offsetting?

The properties of a list allow us to extract a value in a list through offsetting with the [] bracket operator. The bracket operator takes in a offset value 0 to n-1 and returns the value to the end user. Ex: >>>marxes = ["Groucho" , " Chico", "Harpo" ] >>> marxes[0] >>> "Groucho" or print(marxes[0]) (This is how you do it in python IDE not interpreter)

The Sorted() function and its use

This sorts a list or value but makes it as a copy not modifying the original file Syntax: x = list [] y = sorted(x) You have to create a copy of the list in another variable and then invoke the sorted() function imputing the list as an argument.

How do you extract items out of a list?

Use the slice [:] operation.

Combining lists?

We can merge lists by using the .extend method to add one list to another. Ex: list1 list2 list1.extend(list2)

How to convert data types into lists?

We make use of the list() function. Ex: list("cat") >>> [ "c", "a", "t"]

Reversing a list and various tricks

>>> marxes = ['Groucho', 'Chico,' 'Harpo'] >>> marxes[::2] ['Groucho', 'Harpo'] Here, we start at the end and go left by 2: >>> marxes[::-2] ['Harpo', 'Groucho'] And finally, the trick to reverse a list: >>> marxes[::-1] ['Harpo', 'Chico', 'Groucho']

Tuples can change variables without creating a temp variable.

>>> password = 'swordfish' >>> icecream = 'tuttifrutti' >>> password, icecream = icecream, password >>> password 'tuttifrutti' >>> icecream 'swordfish'

The different examples of using dict()

A list of two-item tuples: >>> lot = [ ('a', 'b'), ('c', 'd'), ('e', 'f') ] >>> dict(lot) {'c': 'd', 'a': 'b', 'e': 'f'} A tuple of two-item lists: >>> tol = ( ['a', 'b'], ['c', 'd'], ['e', 'f'] ) >>> dict(tol) {'c': 'd', 'a': 'b', 'e': 'f'} A list of two-character strings: >>> los = [ 'ab', 'cd', 'ef' ] >>> dict(los) {'c': 'd', 'a': 'b', 'e': 'f'} A tuple of two-character strings: >>> tos = ( 'ab', 'cd', 'ef' ) >>> dict(tos) {'c': 'd', 'a': 'b', 'e': 'f'}

Sorting a list with Sort() function

The Sort() function sorts the list itself changing the original file. Syntax: y= list[] y.sort() You simple call the function within code and it sorts it.

When you turn a dictionary into a set what occurs?

The dict will turn into a set but will only retain the KEYS. >>> set( {'apple': 'red', 'orange': 'orange', 'cherry': 'red'} ) {'apple', 'cherry', 'orange'}

List() function. What does it do?

The list() function takes in a argument and turns that object to data type into a list.

What makes lists and Tuples different from strings?

They can contain any python object or type. They can also be indexed and manipulated with various methods and functions.

Insert() function

This can be used to insert a item or element by offset. ex: marxes.insert(3, 'Gummo')

remove() function method

This can be used to remove an item from a list if position is not crucial and you may know its content. >>> marxes = ['Groucho', 'Chico', 'Harpo', 'Gummo', 'Zeppo'] >>> marxes.remove('Gummo') >>> marxes ['Groucho', 'Chico', 'Harpo', 'Zeppo']

Combination and Operators

This is helpful if we want to search something and be specific about the set that we are searching within. >>> for name, contents in drinks.items(): ... if contents & {'vermouth', 'orange juice'}: ... print(name) ... screwdriver martini manhattan

update() function?

This is used for dict to copy one dict into another. x_dict1 = {} y_dict2 = {} x_dict1.update(y_dict2)

Append() function

This usually only adds items to the end of a list.

.count() operator

This will check how many times a particular element shows up in a list. You have to provide the argument and it works on the assumption that you know whats in the list for optimal use. Syntax: >>> marxes = ['Groucho', 'Chico', 'Harpo'] >>> marxes.count('Harpo') 1

List() function?

This will create a empty list in the same manner that the list syntax functions. Ex: Empty_list = list() or empty_list = [ ]

del function statement

This will delete an item by using offsetting. Ex: >>> del marxes[-1] >>> marxes ['Groucho', 'Chico', 'Harpo', 'Gummo', 'Zeppo']

Function of dict()

This will turn two-value sequences into dictionaries. First Item = Key Second Item = Value Ex: lol = [ ['a', 'b'], ['c', 'd'], ['e', 'f'] ] X = dict(lol) {'c': 'd', 'a': 'b', 'e': 'f'}

How do you get the difference?

This would get the members of the first set but not the second set. Lay: Gets whatever the other set does not have. Syntax: - or .difference() >>> a - b {1} >>> a.difference(b) {1} >>> bruss - wruss set() >>> wruss - bruss {'cream'}

Comparing data structures:

To review: you make a list by using square brackets ([]), a tuple by using commas, and a dictionary by using curly brackets ({}). In each case, you access a single element with square brackets: >>> marx_list = ['Groucho', 'Chico', 'Harpo'] >>> marx_tuple = 'Groucho', 'Chico', 'Harpo' >>> marx_dict = {'Groucho': 'banjo', 'Chico': 'piano', 'Harpo': 'harp'} >>> marx_list[2] 'Harpo' >>> marx_tuple[2] 'Harpo' >>> marx_dict['Harpo'] 'harp'

Tuple Unpacking?

Tuple unpacking is the coding style of creating a tuple of (n) elements and then assigning them multiple variables as follows: >>> marx_tuple = ('Groucho', 'Chico', 'Harpo') >>> a, b, c = marx_tuple >>> a 'Groucho' >>> b 'Chico' >>> c 'Harpo'

What is the main difference between tuples and lists.

Tuples are immutable and lists are mutable.

What are Tuples and how do they differentiate from lists?

Tuples are sequences of arbitrary items. Tuples are immutable.

keys() and values() and items() functions

Use these appended to the dictionary to print out the key or values or both syntax: some_dict = {'chap' : 'Gram'} print(some_dict.values()) or some_dict = {'chap' : 'Gram'} print(some_dict.keys()) or some_dict = {'chap' : 'Gram'} print(some_dict.items())

Add or Change a element by its [key]

We can add an item by simply using the key and re-assigning it. Also in a dict we can insert a key-value pair by simply creating the key and assigning the value. How: We call the dict and assign it [key] = value. Ex: some_dict[key_name] = Value This is similar to indexing in lists or strings. Concept: We enter the offset and assign a value. However for dicts we assign a key value pair

Accessing lists within lists and indexing the desired list to extract a value?

We can create a list within a list and access its elements. all_birds =[["Hello, "There"],["Hey","They"] >>> all_birds[1][0] This means [1] access the first list and extract [0] value 0

How would you return the length of the list with the function?

We can invoke the function len and return it through a print statement or assign it to a variable and print the var. Example: print(len(list_name)) or x = len(marxes) print(x)

Adding items to a list?

We use the .append method.

How would you get the length of a list?

We use the len() function. > For its argument it receives the list (). > Ex: len(list_name)

How to get the union off a set?

We use the | or .union() function. >>> a | b {1, 2, 3} >>> a.union(b) {1, 2, 3}

Combining Data structures:

We worked up from simple booleans, numbers, and strings to lists, tuples, sets, and dictionaries. You can combine these built-in data structures into bigger, more complex structures of your own. Let's start with three different lists: >>> marxes = ['Groucho', 'Chico', 'Harpo'] >>> pythons = ['Chapman', 'Cleese', 'Gilliam', 'Jones', 'Palin'] >>> stooges = ['Moe', 'Curly', 'Larry'] We can make a tuple that contains each list as an element: >>> tuple_of_lists = marxes, pythons, stooges >>> tuple_of_lists (['Groucho', 'Chico', 'Harpo'], ['Chapman', 'Cleese', 'Gilliam', 'Jones', 'Palin'], ['Moe', 'Curly', 'Larry']) And, we can make a list that contains the three lists: >>> list_of_lists = [marxes, pythons, stooges] >>> list_of_lists [['Groucho', 'Chico', 'Harpo'], ['Chapman', 'Cleese', 'Gilliam', 'Jones', 'Palin'], ['Moe', 'Curly', 'Larry']] Finally, let's create a dictionary of lists. In this example, let's use the name of the comedy group as the key and the list of members as the value: 66 | Chapter 3: Py Filling: Lists, Tuples, Dictionaries, and Sets >>> dict_of_lists = {'Marxes': marxes, 'Pythons': pythons, 'Stooges': stooges} >> dict_of_lists {'Stooges': ['Moe', 'Curly', 'Larry'], 'Marxes': ['Groucho', 'Chico', 'Harpo'], 'Pythons': ['Chapman', 'Cleese', 'Gilliam', 'Jones', 'Palin']} Your only limitations are those in the data types themselves. For example, dictionary keys need to be immutable, so a list, dictionary, or set can't be a key for another dictionary. But a tuple can be. For example, you could index sites of interest by GPS coordinates (latitude, longitude, and altitude; see "Maps" on page 358 for more mapping examples): >>> houses = { (44.79, -93.14, 285): 'My House', (38.89, -77.03, 13): 'The White House' }

How would you get the intersection of two values.

With the .intersection() function. Syntax: var.intersection(argument/var2)

Get and item by using its Key[]

x = some_dict['Cleese'] print(x) >>> "John" If the key does not exist you will get a error. If they Key is empty youll get a None value.


Related study sets

1.2 how are our ecological footprints affecting our earth

View Set

General Reactions of Carbonyl Compounds

View Set

Ch 12- Corporate Governance and Business Ethics

View Set

22. Race, Ethnicity, & Nation (I): Racism

View Set

Course 5 Module 7. Distribution Rules, Alternatives and Taxation

View Set

Operating Systems: Three Easy Pieces

View Set

Combo with "Respiratory System questions" and 6 others

View Set

Honors Chemistry Everett Study Guide Final Exam

View Set

Ch. 1 Homeostasis and Organelles

View Set

Adolescent Development Chapters 6-7

View Set