Lec 5
Lec 5
1. Understand Tuples
2. Understand Lists
3. Contrast Tuples and Lists
4. Dictionaries; de ning, keys, values,
iterating, operations
1
fi
COMPOUND DATA TYPES
2
◼︎
◼︎
TUPLES
4
◼︎
◼︎
TUPLE UNPACKING
Feature supporting simultaneous assignment of
variables
◦ LHS: tuple of variables
◦ RHS: any iterable type
◦ LHS and RHS must have the same length
Particularly useful for swapping variable values
x = y
y = x
4
◼︎
◼︎
TUPLE UNPACKING
Feature supporting simultaneous assignment of
variables
◦ LHS: tuple of variables
◦ RHS: any iterable type
◦ LHS and RHS must have the same length
Particularly useful for swapping variable values
x = y
y = x
4
◼︎
◼︎
TUPLE UNPACKING
Feature supporting simultaneous assignment of
variables
◦ LHS: tuple of variables
◦ RHS: any iterable type
◦ LHS and RHS must have the same length
Particularly useful for swapping variable values
x = y tmp = x
y = x x = y
y = tmp
4
◼︎
◼︎
TUPLE UNPACKING
Feature supporting simultaneous assignment of
variables
◦ LHS: tuple of variables
◦ RHS: any iterable type
◦ LHS and RHS must have the same length
Particularly useful for swapping variable values
x = y tmp = x
y = x x = y
y = tmp
4
◼︎
◼︎
TUPLE UNPACKING
Feature supporting simultaneous assignment of
variables
◦ LHS: tuple of variables
◦ RHS: any iterable type
◦ LHS and RHS must have the same length
Particularly useful for swapping variable values
4
◼︎
◼︎
TUPLE UNPACKING
Feature supporting simultaneous assignment of
variables
◦ LHS: tuple of variables
◦ RHS: any iterable type
◦ LHS and RHS must have the same length
Particularly useful for swapping variable values
4
◼︎
◼︎
TUPLE UNPACKING
Feature supporting simultaneous assignment of
variables
◦ LHS: tuple of variables
◦ RHS: any iterable type
◦ LHS and RHS must have the same length
Particularly useful for swapping variable values
4
◼︎
◼︎
TUPLE UNPACKING
Feature supporting simultaneous assignment of
variables
◦ LHS: tuple of variables
◦ RHS: any iterable type
◦ LHS and RHS must have the same length
Particularly useful for swapping variable values
4
◼︎
◼︎
MULTIPLE RETURN VALUES
def get_data(aTuple):
nums = () # empty tuple
words = ()
for t in aTuple:
# concatenating with a singleton tuple
nums = nums + (t[0],)
# only add words haven't added before
if t[1] not in words:
words = words + (t[1],)
min_n = min(nums)
max_n = max(nums)
unique_words = len(words)
return (min_n, max_n, unique_words)
6
CHECK YOURSELF!
7
Moodle quiz ‘Tuples’
8
LISTS
9
◼︎
◼︎
◼︎
◼︎
LIST INDEXING
a_list = [] assign a_list to empty list
L = [2, 'a', 4, [1, 2]]
len(L) ➔ evaluates to 4
L[0] ➔ evaluates to 2
L[2]+1 ➔ evaluates to 5
L[3] ➔ evaluates to [1, 2]
L[4] ➔ error (out of range)
i = 2
L[i-1] ➔ evaluates to 'a' since L[1]='a' above
10
CHANGING ELEMENTS
[2,1,3]
[2,5,3]
L
6.0001 LECTURE 5 11 9
◼︎
◼︎
◼︎
CHANGING ELEMENTS
[2,1,3]
[2,5,3]
L
6.0001 LECTURE 5 11 9
◼︎
◼︎
◼︎
CHANGING ELEMENTS
[2,1,3]
[2,5,3]
L
6.0001 LECTURE 5 11 9
◼︎
◼︎
◼︎
CHANGING ELEMENTS
[2,1,3]
[2,5,3]
L
6.0001 LECTURE 5 11 9
◼︎
◼︎
◼︎
Moodle quiz ‘Lists 1’
12
ITERATING OVER A LIST
total = 0 total = 0
for i in range(len(L)): for elem in L:
total += L[i] total += elem
print(total) print(total)
13
◼︎
◼︎
ITERATING OVER A LIST
total = 0 total = 0
for i in range(len(L)): for elem in L:
total += L[i] total += elem
print(total) print(total)
13
◼︎
◼︎
ITERATING OVER A LIST
total = 0 total = 0
for i in range(len(L)): for elem in L:
total += L[i] total += elem
print(total) print(total)
13
◼︎
◼︎
OPERATIONS ON LISTS: ADD
14
◼︎
◼︎
OPERATIONS ON LISTS: ADD
14
◼︎
◼︎
OPERATIONS ON LISTS: ADD
What is a dot?
• lists are Python objects, everything in Python is an object
• objects have data
• objects have methods and functions
• access this information by object_name.do_something()
• will learn more about these later
14
◼︎
◼︎
OPERATIONS ON LISTS: ADD
L = ['a','bc','d','ef'] ➔ L is a list
''.join(L) ➔ returns 'abcdef'
'_'.join(L) ➔ returns 'a_bc_d_ef'
'XYZ'.join(L) ➔ returns 'aXYZbcXYZdXYZef'
17
◼︎
Moodle quiz ‘Lists 2’
18
CONVERT STRINGS TO LISTS
19
◼︎
◼︎
OTHER LIST OPERATIONS
L = [9,6,0,3]
sorted(L) ➔ returns sorted list, does not mutate L
L.sort() ➔ mutates L = [3, 0, 6, 9]
L.reverse() ➔ mutates L = [9, 6, 3, 0]
Many more:
https://docs.python.org/3/tutorial/
datastructures.html
20
◼︎
◼︎
LISTS IN MEMORY
21
LISTS IN MEMORY
21
◼︎
LISTS IN MEMORY
21
◼︎
◼︎
LISTS IN MEMORY
21
◼︎
◼︎
◼︎
LISTS IN MEMORY
21
◼︎
◼︎
◼︎
◼︎
LISTS IN MEMORY
21
◼︎
◼︎
◼︎
◼︎
LISTS IN MEMORY
21
◼︎
◼︎
◼︎
◼︎
◼︎
ALIASES
ALIASES
hot is an alias for warm – changing one changes
hot is an alias for warm – changing one changes
the
other!
the other!
append()
append() has ahas a side
side effect
effect
22
◼︎
◼︎
ALIASES
ALIASES
hot is an alias for warm – changing one changes the
ALIASES
other!
hot append()
is an has
alias a
for side
warm effect
– changing one changes the
hot is an alias for warm – changing one changes
other!
the other!
append()
append() has ahas a side
side effect
effect
6.0001 LECTURE 5 19
22
◼︎
◼︎
ALIASES
ALIASES
hot is an alias for warm – changing one changes the
ALIASES
other!
hot append()
is an has
alias a
for side
warm effect
– changing one changes the
hot is an alias for warm – changing one changes
other!
the other!
ALIASES
append()
append() has ahas a side
side effect
effect
hot is an alias for warm – changing one changes the
other!
append() has a side effect
6.0001 LECTURE 5 19
22
◼︎
◼︎
Moodle quiz ‘Lists 3’
23
CLONING
CLONING A LIST
A LIST
create a new list and copy every element using
chill
Create = cool[:]
a new list and copy every element using
chill = cool[:]
6.0001 LECTURE 5 20
24
◼︎
CLONING
CLONING A LIST
A LIST
create a new list and copy every element using
GA chill
Create
LIST =
a newcool[:]
list and copy every element using
chill = cool[:]
st and copy every element using
ol[:]
6.0001 LECTURE 5 20
6.0001 LECTURE 5 2024
◼︎
CLONING
CLONING A ALIST
A LIST
CLONING LIST
create a new
create listlist
a new andand
copy every
copy element
every using
element using
GA chill
Create
LIST chill =
a new cool[:]
=list and copy every element using
cool[:]
chill = cool[:]
st and copy every element using
ol[:]
6.0001 LECTURE 5
6.0001 LECTURE 5 20 20
6.0001 LECTURE 5 2024
◼︎
calling sorted()
does not mutate
sort()
list, mustAND
assignsorted()
result to a variable
6.0001 LECTURE 5
25
sorted()
callingcalling sort() mutates the list, returns nothing
does not mutate
calling sorted()
sort() AND
does
list, must sorted()
not mutate
assign
list, must assign
result to a variable
result to a variable
6.0001 LECTURE 5 21
6.0001 LECTURE 5
25
sorted()
callingcalling sort() mutates the list, returns nothing
does not mutate
calling sorted()
sort() AND
does
list, must sorted()
not mutate
assign
list, must assign
result to a variable
result to a variable
G LISTS
() mutates the list, returns nothing 6.0001 LECTURE 5 21
ed()
6.0001 LECTURE 5
te
n
able 25
side effects still
possible after mutation
LISTS OF LISTS OF LISTS OF...
6.0001 LECTURE 5
26
side effects still
possible
can after mutation
have nested lists
6.0001 LECTURE 5 22
6.0001 LECTURE 5
26
side effects still
possible
can after mutation
have nested lists
26
MUTATION AND ITERATION
27
MUTATION AND ITERATION
L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6]
for e in L1:
if e in L2:
L1.remove(e)
27
MUTATION AND ITERATION
L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6]
for e in L1:
if e in L2:
L1.remove(e)
27
◼︎
MUTATION AND ITERATION
L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6]
for e in L1:
if e in L2:
L1.remove(e)
27
◼︎
MUTATION AND ITERATION
L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6]
for e in L1:
if e in L2:
L1.remove(e)
27
◼︎
MUTATION AND ITERATION
L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6]
for e in L1:
if e in L2:
L1.remove(e)
27
◼︎
MUTATION AND ITERATION
L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6]
for e in L1:
if e in L2:
L1.remove(e)
27
◼︎
MUTATION AND ITERATION
L1 = [1, 2, 3, 4] L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6] L2 = [1, 2, 5, 6]
for e in L1: for e in L1[:]:
if e in L2: if e in L2:
L1.remove(e) L1.remove(e)
27
◼︎
MUTATION AND ITERATION
L1 = [1, 2, 3, 4] L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6] L2 = [1, 2, 5, 6]
for e in L1: for e in L1[:]:
if e in L2: if e in L2:
L1.remove(e) L1.remove(e)
27
◼︎
MUTATION AND ITERATION
L1 = [1, 2, 3, 4] L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6] L2 = [1, 2, 5, 6]
for e in L1: for e in L1[:]:
if e in L2: if e in L2:
L1.remove(e) L1.remove(e)
copy of
L1
L1 is [2, 3, 4], not [3, 4]!
◦ Python uses an internal counter to keep track of index it is in
the loop
◦ mutating changes the list length but Python doesn’t update
the counter
◦ loop never sees element 2
27
◼︎
MUTATION AND ITERATION
L1 = [1, 2, 3, 4] L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6] L2 = [1, 2, 5, 6]
for e in L1: for e in L1[:]:
if e in L2: if e in L2:
L1.remove(e) L1.remove(e)
copy of
L1
L1 is [2, 3, 4], not [3, 4]!
◦ Python uses an internal counter to keep track of index it is in
the loop
◦ mutating changes the list length but Python doesn’t update
the counter
◦ loop never sees element 2
27
◼︎
MUTATION AND ITERATION
L1 = [1, 2, 3, 4] L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6] L2 = [1, 2, 5, 6]
for e in L1: for e in L1[:]:
if e in L2: if e in L2:
L1.remove(e) L1.remove(e)
copy of
L1
L1 is [2, 3, 4], not [3, 4]!
◦ Python uses an internal counter to keep track of index it is in
the loop
◦ mutating changes the list length but Python doesn’t update
the counter
◦ loop never sees element 2
27
◼︎
Moodle quiz ‘Lists 4’
28
HOW TO STORE GROCERY LIST INFO?
GPPython.book Page 262 Monday, March 19, 2018 4:48 PM
0 milk milk 1
A separate list for each item
Each list must have the same length 1 eggs eggs 12
30
◼︎
◼︎
◼︎
◼︎
DICTIONARY TO THE RESCUE
A BETTER AND CLEANER WAY –
A DICTIONARY
Nice to index item of interest directly (not
always int)
§ nice to index item of interest directly (not always int)
Nice
§ nicetotouse onedata
use one data structure,
structure, no separate
no separate lists lists
A list A dic0onary
0 Elem 1 Key 1 Val 1
… … … …
6.0001 LECTURE 6 43
31
◼︎
◼︎
PYTHON DICTIONARY
'eggs' 12
◦ Key
'bread' 2
◦ Value
cheese' 5
Mutable
jam' 2
◦ Can add/delete mappings
key1 val1 key2 val2 key3 val3 key4 val4 key5 val5
32
◼︎
◼︎
DICTIONARY LOOKUP
'eggs' 12
Looks up the key
'bread' 2
Returns the value associated
with the key cheese' 5
33
◼︎
◼︎
◼︎
◼︎
DICTIONARY OPERATIONS
'milk' 1
add an entry
'eggs' 12
groceries['chicken'] = 4
'bread' 2
test if key in dictionary
cheese' 5
'milk' in groceries ➔ evaluates to True
'butter' in groceries ➔ gives a False jam' 2
delete entry
del(groceries['cheese'])
34
◼︎
◼︎
◼︎
Moodle Quiz
‘Dictionary 1’
35
ITERATING OVER DICTIONARY
'bread' 2
for key in groceries:
print(key, groceries[key]) cheese' 5
milk 1 jam' 2
eggs 12
bread 2
cheese 5
jam 2
36
◼︎
ITERATING OVER DICTIONARY
milk jam' 2
eggs
bread
cheese
jam
37
◼︎
ITERATING OVER DICTIONARY
38
◼︎
ITERATING OVER DICTIONARY
39
◼︎
◼︎
ITERATING OVER DICTIONARY
L = ['bread', 'milk']
for k in groceries:
if k in L:
del(groceries[k]
39
◼︎
◼︎
ITERATING OVER DICTIONARY
L = ['bread', 'milk']
for k in groceries:
if k in L:
del(groceries[k]
39
◼︎
◼︎
ITERATING OVER DICTIONARY
39
◼︎
◼︎
ITERATING OVER DICTIONARY
list of
keys in groceries:
new object
39
◼︎
◼︎
ITERATING OVER DICTIONARY
list of
keys in groceries:
new object
39
◼︎
◼︎
ITERATING OVER DICTIONARY
list of
keys in groceries:
new object
39
◼︎
◼︎
Moodle Quiz
‘Dictionary 2’
40
DICTIONARY KEYS AND VALUES
Values:
◦ Any type (immutable and mutable)
◦ Can be duplicates
◦ Can be lists or even other dictionaries!
Keys:
◦ Must be unique
◦ Immutable type (int, float, string, tuple, bool)
✦ Actually, hashable, but must not be mutated if used as a key
✦ All immutable types are hashable
◦ Careful with floats as keys
42
◼︎
◼︎
◼︎
◼︎
◼︎
◼︎
◼︎
◼︎
Moodle Quiz
‘Dictionary 3’
43
EXAMPLE: ANALYSE SONG LYRICS
44
◼︎
◼︎
◼︎
CREATING A DICTIONARY
def lyrics_to_frequencies(lyrics):
myDict = {}
for word in lyrics:
if word in myDict:
myDict[word] += 1
else:
myDict[word] = 1
return myDict
45
CREATING A DICTIONARY
def lyrics_to_frequencies(lyrics):
myDict = {}
for word in lyrics: Iterate over list
if word in myDict:
myDict[word] += 1
else:
myDict[word] = 1
return myDict
45
CREATING A DICTIONARY
def lyrics_to_frequencies(lyrics):
myDict = {}
for word in lyrics: Iterate over list
myDict[word] += 1
else:
myDict[word] = 1
return myDict
45
CREATING A DICTIONARY
def lyrics_to_frequencies(lyrics):
myDict = {}
for word in lyrics: Iterate over list
45
CREATING A DICTIONARY
def lyrics_to_frequencies(lyrics):
myDict = {}
for word in lyrics: Iterate over list
45
USING A DICTIONARY
def most_common_words(freqs):
values = freqs.values()
best = max(values)
words = []
for k in freqs:
if freqs[k] == best:
words.append(k)
return (words, best)
46
USING A DICTIONARY
def most_common_words(freqs):
Get iterable over values
values = freqs.values()
best = max(values)
words = []
for k in freqs:
if freqs[k] == best:
words.append(k)
return (words, best)
46
USING A DICTIONARY
def most_common_words(freqs):
Get iterable over values
values = freqs.values()
best = max(values)
Can apply max() to an iterable
words = []
for k in freqs:
if freqs[k] == best:
words.append(k)
return (words, best)
46
USING A DICTIONARY
def most_common_words(freqs):
Get iterable over values
values = freqs.values()
best = max(values)
Can apply max() to an iterable
words = []
for k in freqs: Iterate over keys in dictionary
if freqs[k] == best:
words.append(k)
return (words, best)
46
EXPLOITING DICTIONARY
PROPERTIES
def words_often(freqs, minTimes):
result = []
done = False
while not done:
temp = most_common_words(freqs)
if temp[1] >= minTimes:
result.append(temp)
for w in temp[0]:
del(freqs[w])
else:
done = True
return result
47
EXPLOITING DICTIONARY
PROPERTIES
def words_often(freqs, minTimes):
result = []
done = False
while not done:
temp = most_common_words(freqs)
if temp[1] >= minTimes:
result.append(temp)
for w in temp[0]:
del(freqs[w]) mutate dictionary to remove
else: the words that have been
processed
done = True
return result
47