Professional Documents
Culture Documents
Topic6 List Tuples Sets Dictionaries
Topic6 List Tuples Sets Dictionaries
Topic 6
List, Tuples, Dictionaries, and Sets
Fall 2021
Michael S. Brown
EECS Department
York University
• We can bind variables to these objects and access the data stored
inside through a single variable name.
• Learn how we can pass list, tuple, set, dictionary objects to functions
and the difference with pass by value and pass by reference.
x = [1, 2, 3, 4, 5] x = 1, 2, 3, 4, 5
or
This is a tuple, it
behaves similar to
a list, but you can't
modify it. (More
details later
in this lecture)
EECS1015 – York University -- Prof. Michael S. Brown 5
Items in the list can be multiple types
List Tuple
Each item in a List can be whatever Same for tuples, you can mix the datatype.
data type you want. Below is mixing Below is a mixture of strings and floats.
strings and integers.
x = ["EECS", 1012, "EECS", 1015] x = ("Euro", .64, "USD", .75)
x = [-45, 6, 0, 72, 34, 39, 98, -1345, 939, 10, 40, 33]
print("list x has %d elements" % ( len(x) ))
y = []
print("list y has %d elements" % ( len(y) ))
z = ["Hello", "EECS", 1015, "Fall", 2020", "York"]
print("list z has %d elements" % ( len(z) ))
https://trinket.io/python/15874985d2
y = "HELLO"
if y in x:
print("Found")
else:
print("Not found")
Found
Not found
Method Description
append(item) Adds an element at the end of the list
y
16
list method copy() (2/2)
• If we want a copy of a list, we can use the .copy() method
• See below
3
0
https://trinket.io/python/ea25a9f829
https://trinket.io/python/290d6442cf
https://trinket.io/python/14c68646d2
syntax: list[start:end] (including the start item, but not the end item)
T = X[:]
print("T = X[:] (same as .copy() method)")
print(T)
This is a test
This->is->a->test
https://trinket.io/library/trinkets/06d9dc6fde
clear() Removes all the elements from the list Only count()
and index()
copy() Returns a copy of the list are available
count() Returns number of times an item is found in the tuple for tuples.
insert(index,item) Adds an element at the specified position
Q: Why do you
index(item) Finds location of an item in the tuple
think copy() is
remove(item) Removes the item with the specified value not provided?
• Also, since a tuple size cannot change, it is more efficient than a list
(which can dynamically change). You'll learn more about that when
you take a course on "data structures".
https://trinket.io/python/6932e71d9a
x=10
x_sq, x_cb = computeSquareAndCube(x) In this example, we are unpacking the tuple
print("%d %d %d" % (x, x_sq, x_cb))
result to x_sq, and x_cb (as shown in previous slide)
y_sq = computeSquareAndCube(x)
print(y_sq)
In this example, we are binding the tuple to
variable y_sq
10 100 1000
(100, 1000)
https://trinket.io/python/4f3cbaa291
aList = [1, 2, 3, 4, 5]
print(aList)
newList = modifyList( aList.copy() )
print(aList)
print(newList)
https://trinket.io/python/f2beee3d15
EECS1015 – York University -- Prof. Michael S. Brown 39
Returning a mutable type
• We can create a list in a function and return it.
# parameter accepts a mutable object
def createList( ): Function createList() creates a new list and returns
myList = ["A", "B", "C", "D"] it. The list is bound to variable a after the return.
return myList
Global memory
a = None List of variables Data/Objects stored in memory
a = createList() a [1, 2, 3, 4, 5]
print(a)
https://trinket.io/python/31923e72f0
local memory for createList (call stack)
List of variables Data/Objects stored in memory
myList [1, 2, 3, 4, 5]
x = ('This', 'is', 'a', 'test.') This returns the following result (where + is string concat)
separator = "->" string1+stringObj+string2+stringObj+…string6
z = separator.join(x)
print(z)
This is a test
This->is->a->test
https://trinket.io/python/6fd0b0c48e
"curly" brackets
are used. Items keys values
must be specified in "department" "EECS"
key:value pairs.
"coursenum" 1015
Notice the keys and "year" 2021
values are datatypes.
EECS1015 – York University -- Prof. Michael S. Brown
Keys are all strings, values are mixed times (strings and integers)
Accessing items in a dictionary
• Use the key to access an item - dict[key] returns value
associated with key
x = { "department" : "EECS", "coursenum" : 1015, "year" : 2021 } keys values
"department" "EECS"
print(x["department"])
print(x["coursenum"]) "coursenum" 1015
print(x["year"])
"year" 2021
Make sure to put quotes. Keys are not the same as variable names.
For example, here the keys are al strings.
print("Before changes")
print(x)
print("After changes")
print(x)
https://trinket.io/python/b9522333c1
https://trinket.io/python/eb566b8e8d
https://trinket.io/python/eae06757b0
keys values
"country" "Singapore"
"city" "Singapore"
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a "view object" containing the dictionary's keys
update() Updates the dictionary with the specified key-value pairs
values() Returns a "view object" of all the values in the dictionary
backUp = myDict.copy()
myDict.clear()
{}
{'firstname': 'Sharmil', 'lastname': 'Roy', 'age': 20}
https://trinket.io/python/32f0d09078
Sharmili
Sharmili
https://trinket.io/python/b939f3e3c4
{'firstname': 'Sharmili', 'lastname': 'Roy', 'age': 20, 'weight': 55, 'height': 160}
{'firstname': 'Sharmili', 'lastname': 'Roy', 'age': 20, 'weight': 45, 'height': 155, 'eye color': 'brown'}
https://trinket.io/library/trinkets/2c843dcc29
keyView = myDict.keys()
valueView = myDict.values()
print(keyView)
print(valueView)
myDict.update({"height" : 160})
del myDict["age"]
print(myDict)
https://trinket.io/python/ebe0b6ee0f
if "height" in myDict.keys():
print("Key is in dictionary.")
else:
print("Key it not in dictionary.")
https://trinket.io/python/78730bbecd
if "Roy" in myDict.values():
print("Value is in dictionary.")
else:
print("Value is not in dictionary.")
Value is in dictionary.
https://trinket.io/python/76acd30511
https://trinket.io/python/9f469adcf2
local memory for createList (call stack)
List of variables Data/Objects stored in memory
myList {0: "False", 1: "True"}
We can loop over a set, just like lists, tuples, and dictionaries
fruits = {"Banana", "Orange", "Pineapple", "Pear", "Apple", "Grapes"}
for i in fruits:
print(i)
https://trinket.io/python/ca55247f92
False
https://trinket.io/python/957d060f83
Method Description
add(item) Adds an element to the set
union(otherSet) Returns a new set with all items from both set (duplicates removed)
https://trinket.io/python/81ded0f9de
66
set intersection() method
x = {10, 20, 30, 50}
The intersection of two sets is
y = {30, 50, 60, 10}
defined as all the elements that are
print("X")
the same between the two sets.
print(x)
print("Y")
print(y) 1, 10, 9, 20,
print("Intersection of x and y") 21, 55, 78,
z=x.intersection(y) 30, 47
Set A
print(z)
X
{10, 20, 30, 50} 1, 12, 9, 77,
Y 21, 10, 73,
Set B
{10, 30, 50, 60} 31, 47
Intersection of x and y
{10, 30, 50}
https://trinket.io/python/192b23c433 1, 9, 21, Intersection
10, 47 of sets A and B
EECS1015 – York University -- Prof. Michael S. Brown 67
set union() method
x = {10, 20, 30, 50}
The union of two sets is
y = {30, 50, 60, 10}
defined as all the elements of both
print("X")
sets (duplicates are not repeated)
print(x)
print("Y")
print(y) 1, 10, 9, 20,
print("Union of x and y") 21, 55, 78,
z=x.union(y) 30, 47
Set A
print(z)
X
{10, 20, 30, 50} 1, 12, 9, 77,
Y 21, 10, 73,
Set B
{10, 30, 50, 60} 31, 47
Union of x and y
{10, 20, 30, 50, 60}
https://trinket.io/python/fe7661565f 1, 9, 10, 73, 12, Union
77, 78, 47, 20, 21, of sets A and B
EECS1015 – York University -- Prof. Michael S. Brown 55, 30, 31 68
Creating an empty set
• Set and dictionary use the same curly brackets
• If you use empty {}, it will be defined as a dictionary
• To define an empty set, we use the set() with no parameters
value=10
x = {}
x["key"]=value
print(type(x))
x = set() # set as an object
x.add("key")
print(type(x))
https://trinket.io/python/457c50c9bf
https://trinket.io/python/c966a1af26
The list --
[1, 1, 1, 2, 2, 2, 3, 3, 4, 10, 'hello', 99]
Converted to a set -- notice no duplicates
{1, 2, 3, 4, 10, 'hello', 99}
https://trinket.io/python/f36f17be3f
Statement 2
advance to next item in the list
[0, 1, 2, 3, 4, 5, 6, …., 9]
EECS1015 – York University -- Prof. Michael S. Brown 76
For-loop
• Syntax for lists/tuples
variable variable bound to list or tuple object
myList
for items in myList:
first iteration items myList[0] "This"
print("Item: '%s' " % (items))
second iteration items myList[1] "is"
myList[2] "a"
…
The variable in the for-loop statement myList[3] "list"
is bound to an item in the list. This last iteration
items myList[4] "of"
updates at each iteration of the list.
https://trinket.io/python/b7cbe34c85
https://trinket.io/python/a3d3b70bca
Key: CAN
Value: Canada
Key: IN
Value: India
Key: CN
Value: China
Key: EG
Value: Eygpt
https://trinket.io/python/13ae3eacdd
EECS1015 – York University -- Prof. Michael S. Brown 84
Looping through dictionary values
• We can combine our dictionary methods with the loop
• Recall, what does .values() give us? A view into the dictionaries
values. See for-loop below.
countryCodes = {"CAN": "Canada", "IN":"India", "CN":"China", "EG":"Egypt"}
Country: Canada
Country: India
Country: China
Country: Egypt
https://trinket.io/python/fa6feb40af
• Write a program that will print out an order and the total amount as
a bill
• Your input will be a list of order, e.g.:
1, 2, 2, 3, 3, 4 (This example is an order of 6 items)
• Let's assume that an order will have no more than 9 items
• We will have a function to compute the bill based on the order list
from random import randint First – import the function randint() from
module random.
def generateOrder():
numPeople = randint(1,9) # assume max table size is 9 Define function generateOrder.
orderList = [] # create an empty list The function first generates a # between 1-9.
for i in range(numPeople): # for-loop to # of people We then create an empty list.
order = randint(1, 4) # randomly select 1 to 4 items A for loop (using range) is used. At each
orderList.append(order) # add it to the list loop, we generate an order value between 1-4.
return orderList This is appended to the list.
The function returns the list.
def computeBill(orderList):
global priceDict, orderDict # access global variables Define function computeBill(param: list):
total = 0 # set total to 0 Access the global dictionary variables.
print("Number of items ordered %d" % (len(orderList)))# print out # of items Set a total variable to 0.
for order in orderList: # loop through orderList Print out the num of items in the list – using
itemName = orderDict[order] # access name of the order len() function.
itemPrice = priceDict[itemName] # use name to access pirce
total = total + itemPrice # add price to total For each item in the list, get the itemName.
print("-${1:.2f} {0}".format(itemName, itemPrice)) # print out item+price Use the item name to get the price.
Add the price to the total.
print("Total: ${:.2f}".format(total)) # at the end, print total Print out item name and item price.
• Note that I didn't use tuples or sets in our final example, this doesn't
mean they aren't useful.