You are on page 1of 93

EECS 1015

Introduction to Computer Science and Programming

Topic 6
List, Tuples, Dictionaries, and Sets

Fall 2021
Michael S. Brown
EECS Department
York University

EECS1015 – York University -- Prof. Michael S. Brown 1


List, tuples, dictionaries, and set objects
• Lists, tuples, dictionaries, and sets are data types that will allow
you to store multiple items in a single object.

• We can bind variables to these objects and access the data stored
inside through a single variable name.

• All programming languages support some type of data collection.

EECS1015 – York University -- Prof. Michael S. Brown 2


Goal of this lecture
• Learn how to define and use lists, tuples, dictionaries, and sets

• Understand the different between "immutable" and "mutable" objects

• Learn how we can pass list, tuple, set, dictionary objects to functions
and the difference with pass by value and pass by reference.

• Learn the basics of manipulation and "traversing" these data types

EECS1015 – York University -- Prof. Michael S. Brown 3


Part 1: Lists and Tuples

EECS1015 – York University -- Prof. Michael S. Brown 4


Syntax for declaring a list and tuple
List Tuple
To declaring a list surround data with square Declaring a tuple, give a list of data or
brackets ([..]) give a list of data within parenthesis.

x = [1, 2, 3, 4, 5] x = 1, 2, 3, 4, 5
or

x = [] This is an empty list x = (1, 2, 3, 4, 5)

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)

EECS1015 – York University -- Prof. Michael S. Brown 6


Tuple with only one value
• There is a bit of a strange notation to define a tuple of only a single
value
x = (item,)
If we want a tuple with only
x = (100,) a single value, we need to place a
comma after the value.
You can also drop the () and just Why?
have x = 100,
If you think like the interpreter, the
statement:
x = (100)
would be interpreted as a math expression
with only a single literal and (). This would
evaluate to x = 100, not x = a tuple.
So, in order for the interpreter to know
this is a tuple, we need the comma.
EECS1015 – York University -- Prof. Michael S. Brown It is a bit strange (or ugly), but works. 7
List vs. Tuple
• We will first discuss lists and then tuples

• The functionality is similar, however, once defined, tuples cannot be


modified, while lists can be. We can say that a tuple is immutable
(i.e., not changeable) and a list is mutable (i.e., changeable or
dynamic).

EECS1015 – York University -- Prof. Michael S. Brown 8


The list object Items available in the list
x[0] -45 x[-12]
We can bind variables to list objects. The objects store data that
is index by their position in the list. The ordering starts a 0. x[1] 6 x[-11]
Where have you seen this before?
x[2] 0 x[-10]
x = [-45, 6, 0, 72, 34, 39, 98, -1345, 939, 10, 40, 33] x[3] 72 x[-9]
print(x[0])
print(x[-1]) x[4] 34 x[-8]
-45 x[5] 39 x[-7]
33
x[6] 98 x[-6]
List of variables Data/Objects stored in memory x[7] -1345 x[-5]
[-45,…,33] (List)
x x[8] 939 x[-4]
x[0] x[-1] x[9] 10 x[-3]
x[10] 40 x[-2]
x[11] 33 x[-1]

EECS1015 – York University -- Prof. Michael S. Brown 9


Accessing data in a list
Data available in the List

• Similar to strings, we can (1) x[0] -45 x[-12]


access data using an index x[1] 6 x[-11]
operator. x[2] 0 x[-10]
x[3] 72 x[-9]
(1) This will access the integer object (-45)
x[0] stored at this location in the list. x[4] 34 x[-8]
(3) x[5] 39 x[-7]
x[-1] (2) This will access the integer object (33) x[6] 98 x[-6]
stored at the last position of the list.
x[7] -1345 x[-5]

i=5 x[8] 939 x[-4]


(3) We can use variables as indexes into
x[i] the list. x[9] 10 x[-3]
x[10] 40 x[-2]
(2) x[11] 33 x[-1]
EECS1015 – York University -- Prof. Michael S. Brown 10
The length of a list
• We can use the len() function to get the length of the list.

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) ))

list x has 12 elements


list y has 0 elements
list z has 6 elements

https://trinket.io/python/15874985d2

EECS1015 – York University -- Prof. Michael S. Brown 11


Modifying a list item Items available in the List
x[0] -45 x[-12]
We can modify elements in a list too. See line 3 below.
We can assign 50 to x[-2]. This replaces the old value of 40 that was x[1] 6 x[-11]
there.
x[2] 0 x[-10]
x[3] 72 x[-9]
0: x = [-45, 6, 0, 72, 34, 39, 98, -1345, 939, 10, 40, 33]
x[4] 34 x[-8]
1: print(x)
2: x[-2] = 50 x[5] 39 x[-7]
3: print(x)
x[6] 98 x[-6]
[-45, 6, 0, 72, 34, 39, 98, -1345, 939, 10, 40, 33]
x[7] -1345 x[-5]
[-45, 6, 0, 72, 34, 39, 98, -1345, 939, 10, 50, 33]
x[8] 939 x[-4]
https://trinket.io/python/e21b4e9551
x[9] 10 x[-3]
List of variables Data/Objects stored in memory x[10] 40 50 x[-2]
x [-45,…,50, 33] (List) x[11] 33 x[-1]
x[-2]
EECS1015 – York University -- Prof. Michael S. Brown 12
Checking if an item is in the list
We can use the keyword "in" to check if an item is in a list.
This is a Boolean expression, it evaluates to True or False.
Syntax item in list -> True or False
x = ["EECS", 1012, "EECS", 1015]
if 1012 in x:
print("Found")
else:
print("Not found")

y = "HELLO"
if y in x:
print("Found")
else:
print("Not found")
Found
Not found

EECS1015 – York University -- Prof. Michael S. Brown https://trinket.io/python/b68e553bf9 13


List methods
• Just like strings, lists are objects that have associated methods.
• We will discuss the following:

Method Description
append(item) Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list


count() Returns number of times an item is found in the list
insert(index,item) Adds an element at the specified position

index(item) Finds location of an item in the list

remove(item) Removes the item with the specified value

EECS1015 – York University -- Prof. Michael S. Brown 14


list method – append(item) and clear()
append() – adds an item to the clear() – deletes all items in the
end of the list object list object
x = [1, 2, 3, 4] y = ["A", "B", "C", "D"]
x.append(5) y.append("X")
print(x) y.append("Y")
x.append(6) print(y)
x.append(7) y.clear()
print(x) print(y)
[1, 2, 3, 4, 5] ["A", "B", "C", "D", "X", "Y"]
[1, 2, 3, 4, 5, 6, 7] []

https://trinket.io/python/49bb5bf6d4 Available in Python 3 (doesn't work on trinket.io)


Cut and paste above into PyCharm

EECS1015 – York University -- Prof. Michael S. Brown 15


list method copy() (1/2)
• Recall in Python when we set a variable equal to another variable, it
doesn't make a copy of the data. Instead, it bounds both variables to
the same object.
• That may cause a problem with lists:
x = [1, 2, 3, 4, 5] Remember, this does not make a copy.
y = x It binds y to the same object x is bound to.
y[0] = -1
print(x)
Changing y is the
print(y)
same as changing x.
[-1, 2, 3, 4, 5]
[-1, 2, 3, 4, 5]

List of variables Data/Objects stored in memory


x [1, 2, 3, 4, 5] (List)

y
16
list method copy() (2/2)
• If we want a copy of a list, we can use the .copy() method
• See below

This makes a copy in Python's memory.


x = [1, 2, 3, 4, 5] y is bound to the copy.
y = x.copy()
y[0] = -1
print(x)
Now y is changing its own list,
print(y)
not the list x is bound to.
[1, 2, 3, 4, 5]
[-1, 2, 3, 4, 5]

List of variables Data/Objects stored in memory A copy


[1, 2, 3, 4, 5] (List) of the list
x
is created.
[1, 2, 3, 4, 5] (List)
y
y[0] = -1
17
list method count(item)
• Counts the number of times the item given as an argument appears
in the list.
• If it isn't in the list, the count is 0
x = [1, 1, 2, 3, 3, 3, 5]
num3s = x.count(3)
num4s = x.count(4)
print(num3s)
print(num4s)

3
0

https://trinket.io/python/ea25a9f829

EECS1015 – York University -- Prof. Michael S. Brown 18


list method – insert(index, item)
Inserts a new item into the list.
This also modifies the list length! x = [1, 2, 3, 4, 5] x.insert(0, 99) x.insert(4, 101)
x[0] 1 x[0] 99 x[0] 99
x = [1,2, 3, 4, 5] x[1] 1
x[1] 2 x[1] 1
print(x)
x.insert(0, 99) x[2] 3 x[2] 2 x[2] 2
print(x)
x[3] 4 x[3] 3 x[3] 3
x.insert(4, 101)
print(x) x[4] 5 x[4] 4 x[4] 101
[1, 2, 3, 4, 5] X[5] 5 x[5] 4
[99, 1, 2, 3, 4, 5]
Insert at index 0, X[6] 5
[99, 1, 2, 3, 101, 4, 5]
item 99. All other Insert at index 4,
item's indices are item 101. All indices
https://trinket.io/python/fffb96c4a7 adjusted. after 4 are adjusted.

EECS1015 – York University -- Prof. Michael S. Brown 19


list method – index(item)
• Find the index of an item in the list
• Note, this causes an error if the item isn't in the list, so check first.
myList = ["Fun", "Time", "With", "Python", "Yeah!", "LOL", "MLG", "Clutch"]
myStr = input("Word to find (Q to exit): ")
while (myStr != "Q"):
if (myStr in myList):
location = myList.index(myStr)
print("Found at location %d " % (location))
else:
print("Item '%s' not found" % (myStr))

myStr = input("Word to find (Q to exit): ")

https://trinket.io/python/290d6442cf

EECS1015 – York University -- Prof. Michael S. Brown 20


Delete item at index location (del list[index])
You can delete an item
at a particular index. This x = [1, 2, 3, 4, 5] del x[0] del x[3]
effects the size of the list. x[0] 1 x[0] 99 x[0] 2
x = [1,2, 3, 4, 5] x[0] 2
x[1] 2 x[1] 3
print(x)
del x[0] x[2] 3 x[1] 3 x[2] 4
print(x)
x[3] 4 x[2] 4 x[3] 5
del x[3]
print(x) x[4] 5 x[3] 5
[1, 2, 3, 4, 5] deletes item a deletes item at
[2, 3, 4, 5] index 0. List size index 3 (or -1).
[2, 3, 4] changes, items' List size changes.
indices are readjusted.

https://trinket.io/python/14c68646d2

EECS1015 – York University -- Prof. Michael S. Brown 22


list slicing
• Like strings, you can slice a List
• Slicing will create a new List (i.e. it copies the sliced items)

syntax: list[start:end] (including the start item, but not the end item)

additional syntax: list[:end] (this assumes start index=0)


list[start:] (this assumes the end is length+1)
list[:] (all items – this is the same as method copy())

EECS1015 – York University -- Prof. Michael S. Brown 23


list slicing examples
X = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] X List
print("X List") [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
print(X) Y = X[2:5]
[8, 7, 6]
Y = X[2:5]
print("Y = X[2:5]") Z = X[5:]
print(Y) [5, 4, 3, 2, 1]
W = X[:5]
Z = X[5:] [10, 9, 8, 7, 6]
print("Z = X[5:]") T = X[:] (same as .copy() method)
print(Z) [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
W = X[:5] https://trinket.io/library/trinkets/be29de8e1b
print("W = X[:5]")
print(W)

T = X[:]
print("T = X[:] (same as .copy() method)")
print(T)

EECS1015 – York University -- Prof. Michael S. Brown 24


List unpacking
• We can do quick assignment from a list to multiple variables.
• This known as "unpacking".
data = [180, 70.99]
weight, height = data
data = [180, 70.99] # tuple
weight, height = data
print("w:%d h:%d" % (weight, height)) weight, height = [180, 70.99]

Unpacking allows us to quickly


https://trinket.io/python/c8d882c14b assign values in a tuple to
multiple variables.

The alternative to unpacking would be:


weight = data[0]
height = data[1]

EECS1015 – York University -- Prof. Michael S. Brown 26


string method - join for joining lists
• It is common that we have a list of strings
• If you have a list of strings, you can join them together using join.
• The string calling join will be used as the "separator" of the joined
strings – see example.
x = ['This', 'is', 'a', 'test.'] Syntax
y = " "
z = y.join(x) stringObj.join([string1,string2,string3,..string6])
print(z)
This returns the following result (where + is string concat)
x = ['This', 'is', 'a', 'test.'] string1+stringObj+string2+stringObj+…string6
separator = "->"
z = separator.join(x)
print(z)

This is a test
This->is->a->test
https://trinket.io/library/trinkets/06d9dc6fde

IMPORTANT: Notice that join() is an method of a


EECS1015 – York University -- Prof. Michael S. Brown 27
string object. The input is a list.
Part 2: Tuples,
Mutable and Immutable Data Types,
Function call by reference or call by value

EECS1015 – York University -- Prof. Michael S. Brown 28


Tuples
• Tuples are just like lists, except that once defined a tuple cannot be
modified
• We call this an "immutable" data type
• Because tuples can't be modified, only two methods are valid.
Method Description
append(item) Adds an element at the end of the list

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?

EECS1015 – York University -- Prof. Michael S. Brown 29


Why Tuples?
• Sometimes you want a list that can't be modified
• E.g., the name of the days, the months in a year

• 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".

EECS1015 – York University -- Prof. Michael S. Brown 30


Tuple example
Days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat")
print(Days)
print(Days[0])
print(Days.index("Fri"))
print(Days.count("Sund"))
print(Days[1:6])
Days[0] = "Sunday" # Error - you can't assign an item to a tuple

('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat')


Sun
5
0
('Mon', 'Tue', 'Wed', 'Thu', 'Fri')

https://trinket.io/python/6932e71d9a

EECS1015 – York University -- Prof. Michael S. Brown 31


Tuple unpacking
• We can do quick assignment from a tuple to multiple variables.
• This known as "unpacking".
data = (180, 70.99)
weight, height = data
data = (180, 70.99) # tuple
weight, height = data
print("w:%d h:%d" % (weight, height)) weight, height = (180, 70.99)

Unpacking allows us to quickly


https://trinket.io/python/88acadd2b0 assign values in a tuple to
multiple variables.

The alternative to unpacking would be:


weight = data[0]
height = data[1]

EECS1015 – York University -- Prof. Michael S. Brown 32


Function return
Remember this example from last lecture?
def computeSquareAndCube(x):
sqred = x * x The return is actual a tuple – look at slide 5
cubed = x * x * x in this PDF for declaring a tuple. We can
return sqred, cubed declare with only commas.

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

EECS1015 – York University -- Prof. Michael S. Brown 33


mutable vs. immutable data types
• You might not realize it, but the List object was the first time we have
been able to modify an object in Python!
• All previous examples, our expressions would create a new object
x = "Hello " This does not change the string, but creates
x = "Hello " + "EECS1015" a new string.
x[0] = "h"

This is not allowed, will cause an TypeError error.


Python will tell you that Type <str> does not allow item assignment.

List of variables Data/Objects stored in memory


"Hello " (string)
x
"Hello EECS1015" (string)

EECS1015 – York University -- Prof. Michael S. Brown 34


Immutable vs. mutable data types
Class/Type Description Immutable (cannot be
changed)
bool Boolean (true/false) YES – Immutable
int Integer YES – Immutable
float Floating-point number YES – Immutable
list Mutable sequence of ordered items NO – Mutable
tuple Immutable sequence of ordered items YES – Immutable
str Character string YES – Immutable
set Immutable collection of unordered items NO – Mutable
dict Associative mapping (dictionary) NO – Mutable

Sorry, I realize on the video


recording, I said that sets are
immutable – that wrong, as you
will see, sets are mutable.
EECS1015 – York University -- Prof. Michael S. Brown 35
Function calls with immutable and mutable
• The difference between mutable and immutable is important when
we deal with function calls
# parameter accepts a mutable object Output
def modifyList( myList ):
del myList[0] [1, 2, 3, 4, 5]
return myList [2, 3, 4, 5]
[2, 3, 4, 5]
# parameter accepts an immutable object
def modifyString( myString ):
Hello
newString = myString[1:] Hello
return newString ello
aList = [1, 2, 3, 4, 5] https://trinket.io/python/31dbda658a
print(aList)
newList = modifyList(aList)
print(aList)
print(newList) Notice that the variable aList has been changed
after calling modifyList()
aString = "Hello"
print(aString)
newString = modifyString(aString) This does not happen to the function modifyString().
print(aString) What is going on?
print(newString)
EECS1015 – York University -- Prof. Michael S. Brown 36
Immutable data: Pass by value
• When we pass immutable data as an argument to a function,
Python makes a copy of the data.
newString = modifyString(aString)

immutable data is copied


# parameter accepts an immutable object Global memory during function call.
def modifyString( myString ):
List of variables Data/Objects stored in memory
newString = myString[1:]
return newString aString "Hello"
newString "ello"
aString = "Hello"
print(aString) local memory (call stack)
newString = modifyString(aString)
print(aString) List of variables Data/Objects stored in memory
print(newString) myString "Hello"
newString "ello"
immutable data is copied
by return statement.
EECS1015 – York University -- Prof. Michael S. Brown 37
Mutable data: Pass by reference
• When we pass mutable data as an argument to a function, Python does
not copy the data. Instead the parameter is bound to the
mutable object in the argument list. We call this pass by reference.
newString = modifyList( myList )
mutable data is passed by reference.
# parameter accepts a mutable object Global memory the parameter is bound to the argument.
def modifyList( myList ):
List of variables Data/Objects stored in memory
del myList[0] [1, 2, 3, 4, 5]
return myList aList
newList
aList = [1, 2, 3, 4, 5]
print(aList) local memory (call stack)
newList = modifyList(aList)
print(aList) List of variables Data/Objects stored in memory
print(newList) myList

The parameter myList is bound to the same object given as


an argument to the function. (We can say it references the
EECS1015 – York University -- Prof. Michael S. Brown
same object). When we do a return, we are actually 38
returning the same object passed to the function.
Mutable data: Pass by reference
• We call functions that modify mutable data: modifiers
• We call the modifications: side effects
• What if you didn't want to change your list, what could you do?
• Make a copy of the list while doing the call.
# parameter accepts a mutable object
def modifyList( myList ):
del myList[0]
return myList

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]

EECS1015 – York University -- Prof. Michael S. Brown 40


string method - join for joining tuples
• The string method join() can also take a tuple as input
• The strings in the tuple are joined to a new string
x = ('This', 'is', 'a', 'test.') Syntax
y = " "
z = y.join(x)
print(z) stringObj.join((string1,string2,string3,..string6))

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

EECS1015 – York University -- Prof. Michael S. Brown 41


Part 3: Dictionaries

EECS1015 – York University -- Prof. Michael S. Brown 42


Python dictionary
• A dictionary stores items based on key-value pairs
• We call this an unordered collection, since there is no specified order
of the keys

Syntax x = { "department" : "EECS", "coursenum" : 1015, "year" : 2021 }

key: value key: value key: value

"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.

EECS1015 – York University -- Prof. Michael S. Brown 44


Adding and changing dictionary items
• We can also add and change dictionaries items using the [] notation
x = { "department":"EECS", "coursenum":1015, "year":2021 }

print("Before changes")
print(x)

x["semester"]="fall" # add an item (key="semester", value="fall")


x["coursenum"]=1012 # changes value for item with key="coursenum"

print("After changes")
print(x)

https://trinket.io/python/b9522333c1

EECS1015 – York University -- Prof. Michael S. Brown 45


Another example
# define a dictionary Defines a dictionary.
myDict = {"firstname":"Sharmil", "lastname":"Roy", "age": 20}
Access dictionary items
print(myDict["firstname"] + " " + myDict["lastname"]) using keys and [] notation.
myDict["firstname"] = "Sharmili"
Changes an item.
# Adding new key-values
myDict["height"] = 180 Adds new items to the
myDict["weight"] = 55 dictionary.

print("%s (W:%d H:%d)" % (myDict["firstname"], myDict["weight"], myDict["height"]))

# print out the dictionary


print(myDict)

https://trinket.io/python/eb566b8e8d

EECS1015 – York University -- Prof. Michael S. Brown 46


Defining an empty dictionary
• You can define an empty dictionary var={}
• Items can be added later
# define an empty dictionary Defines an empty dictionary.
myDict = {}
print("Enter key, value pairs. Enter Q for the key to quit")
Do a for-loop until the user
key = ""
while (key.upper() != "Q"): types in a "q"/"Q" as a key.
key = input("Enter a key: ")
if (key.upper() != "Q"): Input key/value pairs and
value = input("Enter a value: ") add them to the dictionary.
myDict[key] = value
Q. What would happen if the user
print("Your dictionary") input a key already provided?
print(myDict)

https://trinket.io/python/eae06757b0

EECS1015 – York University -- Prof. Michael S. Brown 47


Restrictions on keys
• Keys can only be immutable types (Boolean, Float, String, Integer)

• A key can only appear once

• A key can only have one associated value

EECS1015 – York University -- Prof. Michael S. Brown 48


Restrictions on values
• There are no restrictions on values (items) associated with a key
• For example, a value can a mutable type – we will talk about this more in the
next lecture

• Two keys can have the same value


myDict = { "country":"Singapore", "city":"Singapore" }

keys values
"country" "Singapore"
"city" "Singapore"

EECS1015 – York University -- Prof. Michael S. Brown 49


Dictionary object methods
• The following is a list of useful methods for dictionaries:

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

EECS1015 – York University -- Prof. Michael S. Brown 50


Dictionary clear() and copy()
• Just like lists, dictionaries are mutable. We can delete all items with
clear. We can make a copy of a directionary with copy().
# define a dictionary
myDict = {"firstname":"Sharmili", "lastname":"Roy", "age": 20}

backUp = myDict.copy()
myDict.clear()

# all items removed


print(myDict)

# print the copy we made


print(backUp)

{}
{'firstname': 'Sharmil', 'lastname': 'Roy', 'age': 20}

https://trinket.io/python/32f0d09078

EECS1015 – York University -- Prof. Michael S. Brown 51


Dictionary method – get(key)
• This is a method to get a value associated with a key
• This is the same as using the [] notation

myDict = {"firstname":"Sharmili", "lastname":"Roy", "age": 20}

print(myDict.get("firstname")) # same as ["firstname"]


print(myDict["firstname"]) # same as .get("firstname")

Sharmili
Sharmili

https://trinket.io/python/b939f3e3c4

EECS1015 – York University -- Prof. Michael S. Brown 52


Dictionary method – items()
• This method returns a tuple of tuples, where each tuples is a key,
value pair from the dictionary
myDict = {"firstname":"Sharmili", "lastname":"Roy", "age": 20}
myDict["weight"] = 55
myDict["height"] = 160
The items() method returns a tuple.
#
allItems = myDict.items() Each item in the tuple is a (key,value)
pair from the dictionary.
for i in range(len(allItems)):
print(allItems[i]) Simple for loop prints out
all items in the tuple. The
range() function is used
('firstname', 'Sharmili') to generate a sequence
('lastname', 'Roy') from 0..# of items in the tuple.
('age', 20)
('weight', 55)
('height', 160) https://trinket.io/python/9117d3c1ec
EECS1015 – York University -- Prof. Michael S. Brown 53
Dictionary method – update()
• We can update our dictionary using update()
• Update allows us to make multiple changes at once
myDict = {"firstname":"Sharmili", "lastname":"Roy", "age": 20}

myDict.update({"weight" : 55}) # same as myDict["weight"] = 55


myDict.update({"height" : 160})
print(myDict)

myDict.update({"height" : 155, "weight" : 45, "eye color": "brown"})


print(myDict)
This line of code will update
items already in the dictionary and
add a new item ("eye color":"brown").

{'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

EECS1015 – York University -- Prof. Michael S. Brown 54


Dictionary methods – keys() and values()
• keys() returns a 'view object' of all the keys in the dictionary
• values() returns a 'view object' of all the values in the dictionary
• View objects are variables that provide a "view" into another object
• When the dictionary is updated, the view object values will be updated
myDict = {"firstname":"Sharmili", "lastname":"Roy", "age": 20}

keyView = myDict.keys()
valueView = myDict.values()

print(keyView)
print(valueView)

myDict.update({"height" : 160})

print(keyView) dict_keys(['firstname', 'lastname', 'age'])


dict_values(['Sharmili', 'Roy', 20])
print(valueView) dict_keys(['firstname', 'lastname', 'age', 'height'])
dict_values(['Sharmili', 'Roy', 20, 160])

EECS1015 – York University -- Prof. Michael S. Brown 55


deleting an item – del dict[key]
• Similar to lists, we can delete items using the key

myDict = {"firstname":"Sharmili", "lastname":"Roy", "age": 20}

del myDict["age"]

print(myDict)

{'firstname': 'Sharmili', 'lastname': 'Roy'}

https://trinket.io/python/ebe0b6ee0f

EECS1015 – York University -- Prof. Michael S. Brown 56


Checking if a key exists
• We can check if a key is already in the dictionary by examining the
keys() view object.

myDict = {"firstname":"Sharmili", "lastname":"Roy", "age": 20}

if "height" in myDict.keys():
print("Key is in dictionary.")
else:
print("Key it not in dictionary.")

Key is not in dictionary.

https://trinket.io/python/78730bbecd

EECS1015 – York University -- Prof. Michael S. Brown 57


Checking if a value exists
• We can check if a valye is already in the dictionary by examining the
values() view object.

myDict = {"firstname":"Sharmili", "lastname":"Roy", "age": 20}

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

EECS1015 – York University -- Prof. Michael S. Brown 58


Dictionary slicing?
• The dictionary object does not support slicing
• Slicing is based on an index range
• Dictionary items cannot be accessed by index – only "keys"

EECS1015 – York University -- Prof. Michael S. Brown 59


Dictionary and function calls
• Remember that list and dictionaries are mutable
• When we pass to a function, the dictionary is passed by reference
• Modifications to the dictionary in the function changes all variables
bound to that object
Because the parameter here is mutable,
def updateAge( dictVar, age ): the parameter dictVar is bound to the same
dictVar["age"] = age
object as the calling argument (in this case
myDict = {"name":"Mahsa", "age":19}
myDict). Changing dictVar in the function
print(myDict) will change the object.
updateAge(myDict, 20)
print(myDict) These changes will be seen when we
access myDict later.
{'name': 'Mahsa', 'age': 19}
{'name': 'Mahsa', 'age': 20}
https://trinket.io/library/trinkets/473218585d

EECS1015 – York University -- Prof. Michael S. Brown 60


Dictionary can be return from functions
• Like lists, we can also return dictionaries
# parameter accepts a mutable object
def createDict( ): Function createList() creates a new list and returns
myDict = {0: "False", 1: "True"} it. The list is bound to variable a after the return.
return myDict
Global memory
a = None List of variables Data/Objects stored in memory
a = createDict() a {0: "False", 1: "True"}
print(a)

https://trinket.io/python/9f469adcf2
local memory for createList (call stack)
List of variables Data/Objects stored in memory
myList {0: "False", 1: "True"}

EECS1015 – York University -- Prof. Michael S. Brown 61


Part 4: Sets

EECS1015 – York University -- Prof. Michael S. Brown 62


Set collection
• A "set" is another data type provide by python
• A "set" is an unordered, collection that does not allow duplicates
• Note: set data items must be immutable (just like dictionary keys)
Syntax to define a set:
fruits = {"Banana", "Orange", "Pineapple", "Pear", "Apple", "Grapes"}

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

EECS1015 – York University -- Prof. Michael S. Brown 63


Checking if item is in the set
• We can use the "in" keyword to check if something is in the set

fruits = {"Banana", "Orange", "Pineapple", "Pear", "Apple", "Grapes"}

result = "Kiwi" in fruits


print(result)

False

https://trinket.io/python/957d060f83

EECS1015 – York University -- Prof. Michael S. Brown 64


Set methods
• Some useful methods for sets:

Method Description
add(item) Adds an element to the set

remove(item) Removes an element from the set

clear() Clears all items in the set

copy() Returns a copy of the set


intersection(otherSet) Returns a new set with items that exist in this set and the otherSet

union(otherSet) Returns a new set with all items from both set (duplicates removed)

EECS1015 – York University -- Prof. Michael S. Brown 65


set method add() and remove()
• As the method names imply, this allows us to add and remove items

x = {10, 20, 30, 50}


x.add(40)
print(x)
x.remove(50)
print(x)

{10, 20, 30, 40, 50}


{10, 20, 30, 40}

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

EECS1015 – York University -- Prof. Michael S. Brown 69


Part 5: List, set, tuple as functions

EECS1015 – York University -- Prof. Michael S. Brown 70


list() as a function
• Use list() as a function to convert other collections into a list
• When applied to a dictionary, only the keys are converted
tupleA = ("Red", "Green", "Blue")
dictB = {1:"One", 2:"Two", 3:"Three"}
setC = {-10, -20, -30, -40}
# convert to list
listA = list(tupleA)
listB = list(dictB) # <- will convert keys only
listC = list(setC)
print(listA)
print(listB)
print(listC)

['Red', 'Green', 'Blue']


[1, 2, 3]
[-40, -30, -20, -10]

EECS1015 – York University -- Prof. Michael S. Brown 71


tuple() as a function
• Use tuple() as a function to convert other collections into a set
• When applied to a dictionary, only the keys are converted
listA = ["Red", "Green", "Blue"]
dictB = {1:"One", 2:"Two", 3:"Three"}
setC = {-10, -20, -30, -40}
# convert to sets
tupleA = tuple(tupleA)
tupleB = tuple(dictB) # <- will convert keys only
tupleC = tuple(listC)
print(tupleA)
print(tupleB)
print(tupleC)

('Red', 'Green', 'Blue')


(1, 2, 3)
(-40, -30, -20, -10)

EECS1015 – York University -- Prof. Michael S. Brown 72


set() as a function
• Use set() as a function to convert other collections into a set
• When applied to a dictionary, only the keys are converted
tupleA = ("Red", "Green", "Blue")
dictB = {1:"One", 2:"Two", 3:"Three"}
listC = [-10, -20, -30, -40]
# convert to sets
setA = set(tupleA)
setB = set(dictB) # <- will convert keys only
setC = set(listC)
print(setA)
print(setB)
print(setC)

{'Red', 'Green', 'Blue'}


{1, 2, 3}
{-40, -30, -20, -10}

https://trinket.io/python/c966a1af26

EECS1015 – York University -- Prof. Michael S. Brown 73


set() as a function
• If you apply set to a list or tuple that duplicates
• The resulting set will not have duplications
myList = [1,1,1,2,2,2,3,3,4,10,"hello", 99]
mySet = set(myList)
print("The list --")
print(myList)
print("Converted to a set -- notice no duplicates")
print(mySet)

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

EECS1015 – York University -- Prof. Michael S. Brown 74


Part 6: For-loops with lists, tuples,
dictionaries and sets

EECS1015 – York University -- Prof. Michael S. Brown 75


For loop for lists, tuples, dictionaries, & sets
• Recall from our prior lecture how a for-loop works
A range of values, or a list of items.
[0, 1, 2, 3, 4, 5, 6, …., 9]
Recall that for-loops Condition: still
process items have items in the
in a list. list?
process item
In our earlier examples,
we used the range() Statement 1
function to generate Out or range repeat
a numerical sequence. (no more items) for all
Statement 2 items
Now we can use
a list, tuple, or dictionary. Statement 3

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.

EECS1015 – York University -- Prof. Michael S. Brown 77


For-loop for lists
myList = ["This", "is", "a", "list", "that", "has", "seven", "words."] Loop #1
Item: 'This'
print("Loop #1") Note that the variable Item: 'is'
for items in myList:
items is assigned the Item: 'a'
print("Item: '%s; " % (items))
values from the list Item: 'list'
print("Loop #2") at each loop iteration. Item: 'that'
for i in range(len(myList)): Item: 'has'
print("Item: '%s' " % (myList[i])) Alternatively, we could use Item: 'seven'
an index range and access Item: 'words.'
using the list[] notation. Loop #2
https://trinket.io/library/trinkets/a783d57f25 Loop #1 is preferred in Python. Item: 'This'
Item: 'is'
Item: 'a'
Item: 'list'
Item: 'that'
Item: 'has'
Item: 'seven'
Item: 'words.'
EECS1015 – York University -- Prof. Michael S. Brown 78
For-loop versus the "in list" expression

for item in myList: vs. if item in myList:


print("Item: {%s} " % (item)) print("Item %s in the list!" % (item))

NOTE: The for-loop notation is very similar to the


Boolean expression "item in list", which would return
True or False. Because of the for in the statement,
Python knows this is a for-loop.

EECS1015 – York University -- Prof. Michael S. Brown 79


For-loop for tuples
• Processing a tuple is exactly the same as processing a list
myTuple = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat") Loop #1
Item: 'Sun'
print("Loop #1") Note that the variable Item: 'Mon'
for items in myTuple:
items is assigned the Item: 'Tue'
print("Item: '%s' " % items)
values from the list Item: 'Wed'
print("Loop #2") at each loop iteration. Item: 'Thu'
for i in range(len(myTuple)): Item: 'Fri'
print("Item: '%s' " % myTuple[i]) Alternatively, we could use Item: 'Sat'
an index range and access Loop #2
using the list[] notation. Item: 'Sun'
https://trinket.io/python/8faf0477a4 Loop #1 is preferred in Python. Item: 'Mon'
Item: 'Tue'
Item: 'Wed'
Item: 'Thu'
Item: 'Fri'
Item: 'Sat'

EECS1015 – York University -- Prof. Michael S. Brown 80


For-loop for sets
• We can loop through all items in a set
• Note that we cannot do indexing into a set, because it has no order

mySet = {"A", "B", "D", "E", "G", "Z", "X"} Loop #1


Item: 'A'
print("Loop #1") Note that the variable Item: 'B'
for items in mySet:
items is assigned the Item: 'D'
print("Item: '%s' " % (items))
values from the set Item: 'E'
at each loop iteration. Item: 'G'
Item: 'Z'
Item: 'X'

https://trinket.io/python/b7cbe34c85

EECS1015 – York University -- Prof. Michael S. Brown 81


Empty lists and tuples?
• What if a list or tuple is empty? Then the loop will have no items to
iterate through.

myList = [] # create an empty list


print("Loop #1")
for items in myList: List is empty, so the for-loop
print("Item: '%s' " % (items))
doesn't have any items
print("Done")
to loop through.

https://trinket.io/python/a3d3b70bca

EECS1015 – York University -- Prof. Michael S. Brown 82


For-loop for dictionaries
• Dictionaries are a bit different than lists, why?
• Dictionaries have pairs of values stored (key and value)
• So, what does the loop variable bind to? the key

for key in myDict:


print("Key: {} ".format(key))
print("Value: {} ".format(myDict[key]))

EECS1015 – York University -- Prof. Michael S. Brown 83


For-loop dictionary example
countryCodes = {"CAN": "Canada", "IN":"India", "CN":"China", "EG":"Egypt"}

for key in countryCodes:


print("Key: {} ".format(key))
print("Value: {} ".format(countryCodes[key]))

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"}

for items in countryCodes.values():


print("Country: {} ".format(items))

Country: Canada
Country: India
Country: China
Country: Egypt
https://trinket.io/python/fa6feb40af

EECS1015 – York University -- Prof. Michael S. Brown 85


Looping through both key and value!
• Remember the items() method, it returned a list of tuples.
• Each tuple is a key, value pair.
• In this case, we are looping through the list and "unpacking" the
tuple at each iteration

for keyVar, valueVar in myDict.items():


print("Key: {} ".format(keyVar))
print("Value: {} ".format(valueVar))

EECS1015 – York University -- Prof. Michael S. Brown 86


Looping through both key and value!
• The items() method returns a list of tuples
• The code, country is unpacking the tuples at each iteration

countryCodes = {"CAN": "Canada", "IN":"India", "CN":"China", "EG":"Egypt"}

for code, country in countryCodes.items():


print("Code: {} Country: {}".format(code, country))

Code: CAN Country: Canada


Code: IN Country: India
Code: CN Country: China
Code: EG Country: Egypt
https://trinket.io/python/90687eeeab

EECS1015 – York University -- Prof. Michael S. Brown 87


Part 7: Putting it all together

EECS1015 – York University -- Prof. Michael S. Brown 88


Simple menu order
• You run a small international restaurant that has only four items:
(1) Masala Dosa $4.25
(2) Jianbing $2.88
(3) Falafel $5.15
(4) Pizza $8.50

• 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

EECS1015 – York University -- Prof. Michael S. Brown 89


Before we begin. . let's think about the task
• We will simulate an order with a function
• This function will generate a list of 1 to 9 values (max # of people is 9)
• The items stored in the list will be an order ID, from 1-4

• We will have a function to compute the bill based on the order list

• We can have a dictionary to keep track of the menu item's names


and their prices
• In fact, let's use two dictionaries. One to map the order ID to the menu item
and one to map the menu item to the price.

EECS1015 – York University -- Prof. Michael S. Brown 90


Example solution
• Because this requires more than 1 slide to put the solution on, I'm
going to show it slightly out of order

• See the following slides

• The code is here: https://trinket.io/python/e032e1e23d

EECS1015 – York University -- Prof. Michael S. Brown 91


Example code – part 1
priceDict = {"Masala Dosa":4.25, "Jianbing":2.88, "Falafel":5.15, "Pizza":8.50} priceDict
orderDict = {1:"Masala Dosa", 2:"Jianbing", 3:"Falafel", 4:"Pizza"} key value
"Masala Dosa" 4.25
def main(): We create two global variables
order = generateOrder() "Jianbing" 2.88
that are bound to two dictionaries
computeBill(order)
shown here.
"Falafel" 5.15
if __name__ == "__main__":
main() priceDict uses the name of "Pizza" 8.50
the food item as the key and the
price as the value.
We will use the special Main function: orderDict
variable __name__ to This will get the order list orderDict uses the order ID (1-4) key value
call our main function. from the function as the key and the name of the 1 "Masala Dosa"
We learned this in the generateOrder(). food item a the value.
last lecture on Functions. Note that we can use integers 2 "Jianbing"
This is a preferred way to The list is passed as an as keys. This is allowed for
write programs in Python. argument that will compute dictionaries. 3 "Falafel"
and print the bill.
4 "Pizza"

EECS1015 – York University -- Prof. Michael S. Brown 92


Example code – part 2 NOTE: In our program the code on this slide
appears before the code on the prior slide.

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.

When loop is done, print out the total.

EECS1015 – York University -- Prof. Michael S. Brown 93


Putting it all together
• As with Topic 5, one beautiful thing about programming is that you
can have many different designs that are all valid

• I purposely used two dictionaries where the value of one dictionary


was used as the key of another dictionary.

• Feel free to re-write the program your own way

• Note that I didn't use tuples or sets in our final example, this doesn't
mean they aren't useful.

EECS1015 – York University -- Prof. Michael S. Brown 94


Summary
• We have learned about lists, tuples, sets, and dictionaries
• These are data types that allow use to store multiple items
• Lists, dictionaries, and sets are mutable
• We need to be aware when we use mutable objects
• If we have multiple variables bound to a mutable object, they are all
accessing the same object
• We can pass and return lists, sets, tuples, and dictionaries to
functions
• When passing to a function, mutable data is passed by "reference"
• We saw how to loop through lists using for-loops
• With dictionaries we often need to use methods keys(), values(), items() with
our for-loop

EECS1015 – York University -- Prof. Michael S. Brown 95

You might also like