Python Collections: Lists, Tuples, Dictionaries, and Sets¶

In this section, we begin to see the nature of Python objects. Each of the elements described in this presentation (lists, tuples, dictionaries, and sets) is a class of objects. For each class, Python has defined methods. These are functions which act on an instantiated object of the class. So for example, if we have a list object named animals, we can add items to that list object using the append method by writing animals.append(). As we introduce each class of objects, there is a reference to a tutorial on the class and a second reference outlining the methods that are defined for that class.

Lists¶

A Python list is a collection of changeable data objects. These objects do not have to be of the same data type. However, it is most often true that the reason they are in a given list is that they are similar. Elements in a list can be changed, and they have order. Therefore, we can refer to an element by its index.

References

W3 Schools Tutorial on Lists

W3 Schools Python List Methods



Updated 8/23/23
Donald R. Falkenburg

EX1.3.1 Indexing Elements in a List¶

The list things contains 5 items--two strings, one float, one integer, and one boolean variable (True).

In [4]:
# EX1.3.1
things=["dog","cat",19.7,5,True]
print(things[0])
print(things[2])
print(things[4])
dog
19.7
True

EX 1.3.2 Adding an element to a list¶

We can append an element to the end of a list using .append(). line 3
We can print the list by referring to its name. Line 4
The sort method is applied to the list animals.sort(). Sort() has no arguments. Line 8
We can insert an element at index i by using .insert(i)

In [7]:
# Ex1.3.2
animals=["dog","cat"]
print("animals is of ",type(animals))
animals.append("parakeet")
print(animals)

animals.append("ardvark")
print(animals)
animals.sort()
print(animals)
animals.insert(2,"mouse")
print(animals)
animals is of  <class 'list'>
['dog', 'cat', 'parakeet']
['dog', 'cat', 'parakeet', 'ardvark']
['ardvark', 'cat', 'dog', 'parakeet']
['ardvark', 'cat', 'mouse', 'dog', 'parakeet']

Comments EX1.3.3¶

Note: Why is the variable type list? The answer is that you assigned it a list value--a series of elements separated by commas and delimited by [ ]. Likewise, when you print a list it appears, again, delimited by square brackets.

EX1.3.3 Find the index of the first occurance of an element in a list.¶

Find the location of the string 'cat' in the list animals. Since it is the the second element in the list, counting from 0, it's index is 1

In [9]:
# EX1.3.3
animals=['ardvark', 'cat', 'dog', 'parakeet']
animals.index('cat')
Out[9]:
1

EX1.3.4 Removing an element from a list¶

The pop method has one argument--the location of the element you want to remove from the list. If that index is -1, it will remove the last element, while an index of -2 would remove the next to last element.

In [7]:
# EX1.3.4
animals=['ardvark', 'pony','cat', 'dog', 'parakeet']
animals.pop(1)
print(animals)
animals.pop(-1)
print (animals)
['ardvark', 'cat', 'dog', 'parakeet']
['ardvark', 'cat', 'dog']

EX1.3.5 Nested Lists¶

Nested lists can be used to represent arrays. EX1.3.5 creates a nested list from three sub lists. This is the way to represent a matrix.

In [1]:
# EX1.3.5
row1=['00','01','02']
row2=['10','11','12']
row3=['20','21','22']
a=[row1,row2,row3]
print(a)
[['00', '01', '02'], ['10', '11', '12'], ['20', '21', '22']]

EX3.3.6 Accessing elements of a nested list¶

You might think that we would access an element in a by a[1,2], but that is NOT correct. The correct access for the element in the second row and third column (matrix) is a[1][2].

In [3]:
# EX1.3.6
row1=['00','01','02']
row2=['10','11','12']
row3=['20','21','22']
a=[row1,row2,row3]
print(a)
print(a[0][0])
print(a[1][2])
[['00', '01', '02'], ['10', '11', '12'], ['20', '21', '22']]
00
12

Tuples¶

References

W3 Schools >Tutorial on Tuples

W3 Schools Tuple Methods

EX1.3.7 Tuples are collections of objects which cannot be altered.¶

(3,5,8,22) is a tuple containing 4 integers. ('aardvark', 'pony','cat', 'dog', 'parakeet') is a tuple containing 5 strings. NOTICE THAT THE ELEMENTS ARE CONTAINED IN PARENTHESES FOR TUPLES, WHILE FOR LISTS, THEY ARE CONTAINED WITHIN SQUARE BRACKETS. Tuples do not support append, insert, pop or do any method which would alter the contents. Why use tuples? Suppose you want to have a representation of the colors of the rainbow. You could use the tuple in the next exercise.

In [8]:
# Ex1.3.7
rainbow=('red','orange','yellow','green','blue','indigo','violet')
print(rainbow.index('green'))
3

EX1.3.8 The count() method for tuples¶

The only other method that belongs to the tuple object is count. count(object) returns the number of times object appears in the tuple.

In [7]:
# Ex1.3.8
rainbow=('red','orange','yellow','green','blue','indigo','violet')
print(rainbow.count('blue'))
colors=('red','blue','orange','yellow','green','blue','indigo','violet','blue')
print(colors.count('blue'))
1
3

Dictionaries¶

References

W3schools Tutorial on Dictionaries

Dictionary Methods

You can define a dictionary by enclosing a comma-separated list of key-value pairs in curly braces ({}). A colon (:) separates each key from its associated value:" reference

dictionary.jpg

EX 1.3.9 Simple Example of Dictionary¶

Suppose we want to create a dictionary which contains the name of the student, sex, seat assignment--a tuple (row,seat), and gpa

In [2]:
# Ex1.3.8
student={"name": "Smith","sex":"F", "seat":(3,4),"gpa":3.3}
print(student)
{'name': 'Smith', 'sex': 'F', 'seat': (3, 4), 'gpa': 3.3}

Comment EX 1.3.9¶

Sometimes in order to make code more readable longer statements are put on multiple lines using a carriage return. In the following example, typing a carriage return after each comma in the dictionary automatically inserts the proper indentation for the remaining elements of the line. Lines 2-5 are interpreted as a single statement. Without the indentation, they would be treated as separate statements, and you will see an error.

In [1]:
# Ex1.3.8a
student={"name": "Smith",
         "sex":"F", 
         "seat":(3,4),
         "gpa":3.3}
print(student)
{'name': 'Smith', 'sex': 'F', 'seat': (3, 4), 'gpa': 3.3}

EX1.3.9 Nested Dictionaries¶

The dictionary in Ex1.3.8 is of limited utility for a class list. It would be great to nest a group of dictionaries together to represent an entire class

By nesting dictionaries, we can create a collection of student data for a class. For each student we have a dictionary like Ex1.3.8 with key words and values within curly brackets {}

Each sub-dictionary is given a keyword. The keyword could be a string like "stud1", or as in the case below, the key is an integer, which acts as an index. In the example below, there are six keyword, value pairs. Each value is another dictionary.

This example serves to illustrate

(1) printing a dictionary
(2) printing a value for keyword=4 which is itself a dictionary. The integer 4 is not an index like we had in a list. If instead of the keyword as an integer we had used keyword "stud4", then that string would be in the brackets[]
(3) printing the value of keyword="name" in sub dictionary identified by keyword 4.

In [4]:
# Ex1.3.9
my_class={  
    1:{"name":"Smith", "ID": 34769,"sex":"F", "seat":(3,4),"gpa":3.3},
    2:{"name":"Brown-Mary", "ID": 28871,"sex":"F", "seat":(3,5),"gpa":2.3},
    3:{"name":"White", "ID": 77987,"sex":"M", "seat":(2,5),"gpa":3.8},
    4:{"name":"Carpenter", "ID": 65534  ,"sex":"F", "seat":(2,2),"gpa":3.0},            
    5:{"name": "Brown-Peter", "ID": 44534,"sex":"M", "seat":(4,3),"gpa":2.7},
    6:{"name":"Perry", "ID": 27778,"sex":"M", "seat":(2,2),"gpa":3.1}                    
        }

print("print the dictionary\n")
print(my_class,"\n")
print("print the value for my_class where the key=4\n")
print(my_class[4],"\n")
print("print the value for keyword name from sub-dictionary with index 4\n")
print(my_class[4]["name"])
print the dictionary

{1: {'name': 'Smith', 'ID': 34769, 'sex': 'F', 'seat': (3, 4), 'gpa': 3.3}, 2: {'name': 'Brown-Mary', 'ID': 28871, 'sex': 'F', 'seat': (3, 5), 'gpa': 2.3}, 3: {'name': 'White', 'ID': 77987, 'sex': 'M', 'seat': (2, 5), 'gpa': 3.8}, 4: {'name': 'Carpenter', 'ID': 65534, 'sex': 'F', 'seat': (2, 2), 'gpa': 3.0}, 5: {'name': 'Brown-Peter', 'ID': 44534, 'sex': 'M', 'seat': (4, 3), 'gpa': 2.7}, 6: {'name': 'Perry', 'ID': 27778, 'sex': 'M', 'seat': (2, 2), 'gpa': 3.1}} 

print the value for my_class where the key=4

{'name': 'Carpenter', 'ID': 65534, 'sex': 'F', 'seat': (2, 2), 'gpa': 3.0} 

print the value for keyword name from sub-dictionary with index 4

Carpenter

Comments EX1.3.9¶

In the print statements the characters \n contained within a string are interpreted as an escape character which produces a line feed. Notice in the output, the blank line between the printed string and the contents of my_class.

EX1.3.10 Dictionary Methods¶

In the next example, we will apply three of the Python dictionary methods described in the second reference to the heading of this subsection.

How to print the keywords for a dictionary. Line 12 applies the method .keys() to my_class

How to get a value for given a keyword. In this case, the value is the sub-dictionary whose key=4. We use the get() methond applied to my_class. line 15.

Get values for 'name', 'ID' and 'gpa' from a sub-dictionary.

https://stackoverflow.com/questions/17330139/python-printing-a-dictionary-as-a-horizontal-table-with-headers

In [3]:
# Ex1.3.10
my_class={  
    1:{"name":"Smith", "ID": 34769,"sex":"F", "seat":(3,4),"gpa":3.3},
    2:{"name":"Brown-Mary", "ID": 28871,"sex":"F", "seat":(3,5),"gpa":2.3},
    3:{"name":"White", "ID": 77987,"sex":"M", "seat":(2,5),"gpa":3.8},
    4:{"name":"Carpenter", "ID": 65534  ,"sex":"F", "seat":(2,2),"gpa":3.0},            
    5:{"name": "Brown-Peter", "ID": 44534,"sex":"M", "seat":(4,3),"gpa":2.7},
    6:{"name":"Perry", "ID": 27778,"sex":"M", "seat":(2,2),"gpa":3.1}                    
        }
# Method .keys() creates a LIST of the keys of the dictionary.  In this case of a nested dictionary,
# this is the index number 1,2,3..6
MyKeys=my_class.keys()
print("keys in dictionary my_class{}\n")
print(MyKeys,"\nl")
rec4=my_class.get(4)
print("sub-dictionary my_class[4]\n")
print(rec4,"\n")
print("value for keyword 'name','ID',and 'gpa' in rec4\n")
print(rec4.get("name"),rec4.get("ID"),rec4.get("gpa"),"\n")
keys in dictionary my_class{}

dict_keys([1, 2, 3, 4, 5, 6]) 
l
sub-dictionary my_class[4]

{'name': 'Carpenter', 'ID': 65534, 'sex': 'F', 'seat': (2, 2), 'gpa': 3.0} 

value for keyword 'name','ID',and 'gpa' in rec4

Carpenter 65534 3.0 

Comments EX1.3.10¶

First note lines 3-9 are a single statement. You can see in this case why it is necessary to use carriage returns to distribute the statement over several lines, making it readable.

In Python indexing always begins at 0. Why do we have numbers in the data running 1,2,3..6? The answer is simple. These are not index numbers. They are key-words. Again, we could use anything here like student_1, student_2,...etc.

EX1.3.11 Pretty Print¶

If you look back at Ex1.3.9 in which we printed the dictionary, you will realize that it is not formatted in a way that would make it useful to use as a reference for the classroom. While there is much more we could say about formatting outputs, for the time being, let me introduce the string format method in Python3. (https://www.w3schools.com/python/ref_string_format.asp).

In lines 10 & 16 we show the print statement with what are called placeholders {}. Each placeholder is assiciate with a variable to be printed, in this case v1,v2,v3. The character following the : in the curly brackets is a blank space, followed by an integer, and the symbol <. This means that the value of v1 will be printed in a frame of 20 characters with left justification (<) and leading spaces which are blanks. If instead of the blank space following the : I wrote {*20>} that would fill the 20 spaces not needed for the value v1 with asterisks, and now it will be right justified. Center justify is indicated by ^.

The print statement on line t0 produces the headings. Statement 11 is a for loop. We will talk about this shortly. For now, however, I'll say two things. First, the statement-- for i in range(1,len(my_class)):-- indicates that there is a block of code following the colon which will be repeated from a value of i=1 and terminated after i reaches the value of the length of the dictionary my_class, which in this case contains six elements.

In [22]:
# Ex1.3.11
my_class={  
    1:{"name":"Smith", "ID": 34769,"sex":"F", "seat":(3,4),"gpa":3.3},
    2:{"name":"Brown-Mary", "ID": 28871,"sex":"F", "seat":(3,5),"gpa":2.3},
    3:{"name":"White", "ID": 77987,"sex":"M", "seat":(2,5),"gpa":3.8},
    4:{"name":"Carpenter", "ID": 65534  ,"sex":"F", "seat":(2,2),"gpa":3.0},            
    5:{"name": "Brown-Peter", "ID": 44534,"sex":"M", "seat":(4,3),"gpa":2.7},
    6:{"name":"Perry", "ID": 27778,"sex":"M", "seat":(2,2),"gpa":3.1}                    
        }
print("{: <20} {: <10} {: <10}".format('name','id','gpa'))
for i in range(1,len(my_class)):
    rec=my_class.get(i)
    v1=rec.get("name")
    v2=rec.get("ID")
    v3=rec.get("gpa")
    print("{: <20} {: <10} {: <10}".format(v1,v2,v3))
name                 id         gpa       
Smith                34769      3.3       
Brown-Mary           28871      2.3       
White                77987      3.8       
Carpenter            65534      3.0       
Brown-Peter          44534      2.7       

Sets¶

"\Sets are used to store multiple items in a single variable.
A set is a collection which is unordered, unchangeable*, and unindexed items. While individual items cannot change value, you can add and remove an item from a set.

References

W3 :chools Tutorial: sets

W3 Schools: Set Methods

EX1.3.12 Creating a set¶

Like dictionaries, sets are constructed by enclosing members of the set within curly brackets {}. The difference is that in a dictionary, the elements are pairs of keys and values. The format is like a list except the delimiters of the set are curly brackets rather than square brackets.
Note: place order is not important. An element is either a member or not.

In [7]:
# Ex1.3.12
animals={'ardvark', 'pony','cat', 'dog'}
birds={'parakeet','eagle','hawk'}
print(animals)
print(birds)
{'dog', 'ardvark', 'cat', 'pony'}
{'eagle', 'parakeet', 'hawk'}

EX1.3.13 Union of sets¶

In [9]:
# Ex1.3.13
animals={'ardvark', 'pony','cat', 'dog'}
birds={'parakeet','eagle','hawk'}
animals=animals.union(birds)
print (animals)
{'dog', 'ardvark', 'cat', 'hawk', 'parakeet', 'eagle', 'pony'}

EX1.3.14 Intersection of sets¶

intersection_update() creates a new set containing members of both sets animals and birds.

In [13]:
# Ex1.3.14
animals={'ardvark', 'pony','cat', 'dog'}
birds={'parakeet','eagle','hawk'}
x=animals.intersection_update(birds)
print (x)
None
In [ ]: