11e. Review: Tuples#
A review of Chapter 11: Tuples, for students who have already studied the chapter. Use the two lists under Concepts covered as a checklist (click a list’s title to hide it), then work through the Questions, which go from the easiest to the hardest. Each question has a suggested answer under Answer. Try the question first, then open the Answer.
Concepts covered#
Python Syntax and Semantics
Creating tuples
A tuple is a sequence of values, indexed by integers, like a list. The values can be any type.
The comma makes the tuple:
t = 'l', 'u', 'p', 'i', 'n'makes a tuple of five strings.Parentheses are not needed, but it is common to use them:
t = ('l', 'u', 'p', 'i', 'n')makes the same tuple.To make a tuple with one element, include a final comma:
t = 'p',makes a tuple. A value in parentheses alone is not a tuple:t = ('p')makes the string'p'.tuple()makes an empty tuple:tuple()is().tuple(SEQUENCE)makes a tuple with the elements of the sequence:tuple('lupin')is('l', 'u', 'p', 'i', 'n').Do not use
tupleas a variable name: it is the name of a built-in function.
Indexing, slicing and operators
TUPLE[INDEX]returns the element at that index:tuple('lupin')[0]is'l'.TUPLE[START:STOP]selects a range of elements:tuple('lupin')[1:3]is('u', 'p').+concatenates tuples:tuple('lup') + ('i', 'n')is('l', 'u', 'p', 'i', 'n').*duplicates a tuple:tuple('ab') * 2is('a', 'b', 'a', 'b').sorted(TUPLE)returns a list, not a tuple:sorted(('b', 'a'))is['a', 'b'].reversed(TUPLE)returns a reversed object.tuple(reversed(TUPLE))makes a tuple from it:tuple(reversed(('a', 'b')))is('b', 'a').
Tuples are immutable
Assigning to an element of a tuple is a
TypeError.Tuples have no methods that change them, like
appendandremove: callingt.remove('l')on a tuple is anAttributeError.Because tuples are immutable, they are hashable, so they can be keys in a dictionary. After this code,
grid[1, 2]is3:grid = {} grid[1, 2] = 3 grid[3, 4] = 7
A tuple can be a value in a dictionary:
{'key': ('a', 'b', 'c')}has a tuple as its value.
Tuple assignment
This assigns the values to the variables from left to right:
a, b = 1, 2
After it,
ais1andbis2.If the left side of an assignment is a tuple, the right side can be any kind of sequence. For example,
username, domain = email.split('@')splits an email address at the@: the first part goes tousername, the second todomain.The number of variables and the number of values must be the same, or it is a
ValueError.To swap the values of two variables, use tuple assignment:
a, b = b, a. The expressions on the right are evaluated before any of the assignments.
Looping through a dictionary with .items()
DICT.items()gives the items of the dictionary, as adict_itemsobject that behaves like a list of tuples: each item is a tuple of a key and its value.This loops through the keys and the values together:
for KEY, VALUE in DICT.items(): BODY
Each time through the loop,
KEYandVALUEget the next key and its value.You can also loop through the items and unpack each one on its own line:
for item in d.items(): key, value = item
Tuples as return values
A function returns one value, but if the value is a tuple, it is like returning several values.
divmod(A, B)returns a tuple of the quotient and the remainder:divmod(7, 3)is(2, 1).Use tuple assignment to store the elements in variables:
quotient, remainder = divmod(7, 3)setsquotientto2andremainderto1.min(SEQUENCE)andmax(SEQUENCE)find the smallest and largest elements of a sequence:min([2, 4, 1, 3])is1, andmax([2, 4, 1, 3])is4.
Argument packing and unpacking
A parameter name that starts with
*packs the arguments into a tuple. Indef mean(*args):,argsis a tuple of the arguments.argsis the conventional name.*before a sequence unpacks it into separate arguments:divmod(*(7, 3))is the same asdivmod(7, 3).Passing a tuple where two arguments are expected is a
TypeError:divmod((7, 3))fails, because the tuple counts as one argument.
Zip
zip(SEQUENCE, SEQUENCE)returns a zip object, which pairs up the elements of the sequences, like the teeth of a zipper.This loops through the pairs:
for pair in zip(scores1, scores2): BODY
Each time through the loop,
pairis a tuple of the two scores.list(zip(SEQUENCE, SEQUENCE))makes a list of tuples.dict(zip(KEYS, VALUES))makes a dictionary from a list of keys and a list of values:dict(zip('ab', [1, 2]))is{'a': 1, 'b': 2}.
Enumerate
enumerate(SEQUENCE)returns an enumerate object, which loops through pairs of an index (starting from 0) and an element.This loops through the indices and the elements:
for INDEX, ELEMENT in enumerate(SEQUENCE): BODY
Comparing and sorting tuples
<compares tuples element by element, from the first: it stops at the first pair that differs, and later elements are not considered.(0, 1, 2000000) < (0, 3, 4)isTrue, because1is less than3, and the2000000is never compared.sorted(ITEMS)sorts a list of tuples by the first element, and uses the second element to break ties.key=FUNCTIONtellssorted(ormaxormin) to useFUNCTIONto compute the sort key for each item.max(ITEMS, key=FUNCTION)returns the item with the largest sort key.minworks the same way for the smallest.
Inverting a dictionary
To invert a dictionary, make a new dictionary where each value maps to a list of the keys that had that value: values are not unique, so one value can go with several keys, but keys are unique.
The loop goes through the keys and the values of the old dictionary:
for key, value in d.items():.
Definitions, etc.
Definitions
DEFINITION: pack is to collect multiple arguments into a tuple.
DEFINITION: unpack is to treat a tuple (or other sequence) as multiple arguments.
DEFINITION: A zip object is the result of calling the built-in function
zip, and can be used to loop through a sequence of tuples.DEFINITION: An enumerate object is the result of calling the built-in function
enumerate, and can be used to loop through a sequence of tuples.DEFINITION: A sort key is a value, or a function that computes a value, used to sort the elements of a collection.
DEFINITION: A data structure is a collection of values, organized to perform certain operations efficiently.
Other ideas
A tuple that holds a mutable value, like a list, is not hashable and cannot be a key in a dictionary.
To check the shape of a data structure, download
structshape.pyand callstructshape(VALUE): it returns a string that describes the structure, for example whether it is a list of tuples or a dictionary of lists.A tuple is a sequence, so
len, loops and the other tools for sequences work with it.
Questions#
All the questions use only tuples, dictionaries, lists, strings, loops, functions and print.
The setup cell below imports math.
# Setup for the questions below (imports, downloads of helper files, ...)
import math
Question 1 (easy): what is displayed?#
Predict what this code displays, then open the Answer to check.
t = 'l', 'u', 'p', 'i', 'n'
print(t)
print(len(t))
Answer
('l', 'u', 'p', 'i', 'n')
5
The comma makes the tuple. t is ('l', 'u', 'p', 'i', 'n'), and len(t) is 5.
Question 2 (easy): what is displayed?#
Predict what this code displays, then open the Answer to check.
t1 = 'p',
t2 = ('p')
print(t1)
print(t2)
print(type(t1))
print(type(t2))
Answer
('p',)
p
<class 'tuple'>
<class 'str'>
A tuple with one element needs a final comma: t1 is ('p',). Parentheses alone do not make a tuple: t2 is 'p'.
Question 3 (easy): what is displayed?#
Predict what this code displays, then open the Answer to check.
print(tuple())
print(tuple('lupin'))
print(tuple([1, 2, 3]))
Answer
()
('l', 'u', 'p', 'i', 'n')
(1, 2, 3)
tuple() makes an empty tuple. tuple(SEQUENCE) makes a tuple with the elements of the sequence: tuple('lupin') is ('l', 'u', 'p', 'i', 'n'), and tuple([1, 2, 3]) is (1, 2, 3).
Question 4 (easy): what is displayed?#
Predict what this code displays, then open the Answer to check.
t = tuple('lupin')
print(t[0])
print(t[1:3])
print(t[-1])
Answer
l
('u', 'p')
n
The bracket operator indexes an element: t[0] is 'l'. The slice operator selects a range: t[1:3] is ('u', 'p'). A negative index counts from the end: t[-1] is 'n'.
Question 5 (easy): what is displayed?#
Predict what this code displays, then open the Answer to check.
print(tuple('lup') + ('i', 'n'))
print(tuple('ab') * 2)
Answer
('l', 'u', 'p', 'i', 'n')
('a', 'b', 'a', 'b')
+ concatenates tuples, and * duplicates a tuple: tuple('lup') + ('i', 'n') is ('l', 'u', 'p', 'i', 'n'), and tuple('ab') * 2 is ('a', 'b', 'a', 'b').
Question 6 (easy): what happens?#
Predict what happens when this code runs, then open the Answer to check.
t = tuple('lupin')
t[0] = 'L'
Answer
1 t = tuple('lupin')
----> 2 t[0] = 'L'
TypeError: 'tuple' object does not support item assignment
Tuples are immutable, so assigning to an element is a TypeError.
Question 7 (easy): what is displayed?#
Predict what this code displays, then open the Answer to check.
grid = {}
grid[1, 2] = 3
grid[3, 4] = 7
print(grid)
print(grid[1, 2])
Answer
{(1, 2): 3, (3, 4): 7}
3
Tuples are hashable, so they can be keys in a dictionary: grid is {(1, 2): 3, (3, 4): 7}. Looking up the tuple (1, 2) gives grid[1, 2] is 3.
Question 8 (easy): what is displayed?#
Predict what this code displays, then open the Answer to check.
a, b = 1, 2
a, b = b, a
print(a, b)
Answer
2 1
The second line swaps the values: after it, a is 2 and b is 1.
Question 9 (easy): what happens?#
Predict what happens when this code runs, then open the Answer to check.
a, b = 1, 2, 3
Answer
----> 1 a, b = 1, 2, 3
ValueError: too many values to unpack (expected 2)
The number of variables and the number of values must be the same, so this is a ValueError.
Question 10 (easy): what is displayed?#
Predict what this code displays, then open the Answer to check.
d = {'one': 1, 'two': 2}
for key, value in d.items():
print(key, '->', value)
Answer
one -> 1
two -> 2
.items() gives each item as a tuple of a key and its value, and the for line unpacks it into key and value. list(d.items()) is [('one', 1), ('two', 2)].
Question 11 (easy): what is displayed?#
Predict what this code displays, then open the Answer to check.
quotient, remainder = divmod(7, 3)
print(quotient)
print(remainder)
Answer
2
1
divmod(7, 3) returns the tuple (2, 1), and tuple assignment stores the elements: quotient is 2 and remainder is 1.
Question 12 (easy): write a function#
Write a function called first_and_last that takes a tuple t and returns a tuple of its first and last elements.
Start from this header (replace ... with the body):
def first_and_last(t):
...
Examples
print(first_and_last(('a', 'b', 'c')))
('a', 'c')
print(first_and_last((7,)))
(7, 7)
Answer
Index the first element and the last element, and return them as a tuple:
def first_and_last(t):
return t[0], t[-1]
Then try: print(first_and_last(('a', 'b', 'c'))).
Question 13 (easy): what is displayed?#
Predict what this code displays, then open the Answer to check.
for index, element in enumerate('abc'):
print(index, element)
Answer
0 a
1 b
2 c
enumerate gives pairs of an index and an element, with the index starting from 0.
Question 14 (medium): what is displayed?#
Both parts loop through the items in a dictionary and display each key and its value. Part a unpacks each item on its own line. Part b unpacks it in the for line. Predict what each part displays, then open the Answer to check.
Part a
counts = {'a': 1, 'b': 2}
for item in counts.items():
key, value = item
print(key, '->', value)
Part b
counts = {'a': 1, 'b': 2}
for key, value in counts.items():
print(key, '->', value)
Answer
Part a: Each time through the loop, item is a tuple of a key and its value, and the assignment unpacks it into key and value. The loop displays a -> 1 and then b -> 2.
a -> 1
b -> 2
Part b: The for line assigns the key and the value directly to key and value. The loop displays the same two lines: a -> 1 and b -> 2.
a -> 1
b -> 2
Both parts display the same lines. Line by line, Part b compared with Part a:
counts = {'a': 1, 'b': 2}— UNCHANGEDfor key, value in counts.items():— CHANGED: this one line does the work of theforline and the unpacking line in Part a.key, value = item— DELETEDprint(key, '->', value)— UNCHANGED
What changed: the two lines for item in counts.items(): and key, value = item became one line, for key, value in counts.items():. What did not change: the dictionary, the print, and the output.
Question 15 (medium): write a function#
Write a function called min_max that takes a sequence t and returns a tuple of its smallest and largest elements.
Start from this header (replace ... with the body):
def min_max(t):
...
Examples
print(min_max([2, 4, 1, 3]))
(1, 4)
print(min_max('banana'))
('a', 'n')
Answer
min finds the smallest element and max finds the largest. Return them as a tuple:
def min_max(t):
return min(t), max(t)
Then try: print(min_max([2, 4, 1, 3])).
Question 16 (medium): write a function#
Write a function called make_dict that takes a list of keys and a list of values, and returns a dictionary that maps each key to the value in the same position.
Start from this header (replace ... with the body):
def make_dict(keys, values):
...
Examples
print(make_dict(['a', 'b'], [1, 2]))
{'a': 1, 'b': 2}
print(make_dict('abc', [1, 2, 3]))
{'a': 1, 'b': 2, 'c': 3}
Answer
zip pairs up the keys and the values, and dict makes a dictionary from the pairs:
def make_dict(keys, values):
return dict(zip(keys, values))
Then try: print(make_dict(['a', 'b'], [1, 2])).
Question 17 (hard): write a function#
Write a function called mean that takes any number of arguments and returns their mean: their sum divided by how many there are.
Start from this header (replace ... with the body):
def mean(*args):
...
Examples
print(mean(1, 2, 3))
2.0
print(mean(1, 2, 3, 10))
4.0
Answer
The parameter *args packs the arguments into a tuple, so sum and len work on it:
def mean(*args):
return sum(args) / len(args)
Then try: print(mean(1, 2, 3)).
Question 18 (hard): write a function#
Write a function called invert_dict that takes a dictionary d and returns its inverse: a new dictionary that maps each value in d to a list of the keys that had that value.
Start from this header (replace ... with the body):
def invert_dict(d):
...
Examples
print(invert_dict({'p': 1, 'a': 1, 'r': 2, 'o': 1, 't': 1}))
{1: ['p', 'a', 'o', 't'], 2: ['r']}
print(invert_dict({'a': 1, 'b': 2, 'c': 1}))
{1: ['a', 'c'], 2: ['b']}
Answer
Loop through the keys and the values. If a value is not a key in the new dictionary yet, add it with a list of one key; if it is already there, append the key to its list:
def invert_dict(d):
new = {}
for key, value in d.items():
if value not in new:
new[value] = [key]
else:
new[value].append(key)
return new
Then try: print(invert_dict({'p': 1, 'a': 1, 'r': 2, 'o': 1, 't': 1})).
Question 19 (hard): what is displayed?#
< compares tuples element by element, from the first. It stops at the first pair that differs, and later elements are not considered. Predict what this code displays, then open the Answer to check.
print((0, 1, 2) < (0, 3, 4))
print((0, 1, 2000000) < (0, 3, 4))
Answer
True
True
Both comparisons are True. In the first, 0 equals 0, and then 1 is less than 3, so the first tuple is smaller. In the second, the same thing happens: 1 is less than 3, so the 2000000 is never compared.
Question 20 (hard): write a function#
Write a function called most_common that takes a dictionary counter that maps each key to a count, and returns the key with the largest count.
Start from this header (replace ... with the body):
def most_common(counter):
...
Examples
print(most_common({'b': 1, 'a': 3, 'n': 2}))
a
print(most_common({'p': 4, 'q': 2}))
p
Answer
Use max with a key function that returns the second element of each item, and take the key of the largest item:
def second_element(t):
return t[1]
def most_common(counter):
return max(counter.items(), key=second_element)[0]
Then try: print(most_common({'b': 1, 'a': 3, 'n': 2})).
Or loop through the items and keep the key with the largest count so far:
def most_common(counter):
best_key = None
best_count = 0
for key, count in counter.items():
if count > best_count:
best_key = key
best_count = count
return best_key
Question 21 (hard): write a function#
Write a function called trimmed_mean that takes any number of arguments, removes the lowest and the highest, and returns the mean of the rest. This question uses min_max from Question 15 and mean from Question 17.
Start from this header (replace ... with the body):
def trimmed_mean(*args):
...
Examples
print(trimmed_mean(1, 2, 3, 10))
2.5
print(trimmed_mean(5, 1, 4, 2, 3))
3.0
Answer
Find the lowest and highest with min_max, convert the arguments to a list so the lowest and highest can be removed, and pass what is left to mean as separate arguments:
def min_max(t):
return min(t), max(t)
def mean(*args):
return sum(args) / len(args)
def trimmed_mean(*args):
low, high = min_max(args)
trimmed = list(args)
trimmed.remove(low)
trimmed.remove(high)
return mean(*trimmed)
Then try: print(trimmed_mean(1, 2, 3, 10)).
This block repeats min_max from Question 15 and mean from Question 17, so you can copy it into a new cell and run it on its own.
Question 22 (hard): write a function#
Imagine a short book: a list of lines, where each line is a string of words separated by spaces. All the words are lowercase, and there is no punctuation. Write a function called make_index that takes a list of lines and returns a dictionary. Each key is a word in the book, and its value is a list of the line numbers where the word appears. Line numbers start at 1. Each line number appears once in a list, even if the word appears more than once on that line. The method line.split() returns a list of the words in line.
Start from this header (replace ... with the body):
def make_index(lines):
...
Examples
print(make_index(['cats sit', 'dogs sit', 'cats sleep']))
{'cats': [1, 3], 'sit': [1, 2], 'dogs': [2], 'sleep': [3]}
print(make_index(['one fish', 'two fish', 'red fish', 'blue fish']))
{'one': [1], 'fish': [1, 2, 3, 4], 'two': [2], 'red': [3], 'blue': [4]}
Answer
Loop through the lines and the words in each line. Add a word to the dictionary the first time it appears, and add the line number if it is not already there:
def make_index(lines):
index = {}
for i in range(len(lines)):
for word in lines[i].split():
if word not in index:
index[word] = []
if i + 1 not in index[word]:
index[word].append(i + 1)
return index
Then try: print(make_index(['cats sit', 'dogs sit', 'cats sleep'])).
The same function with enumerate, which gives the position of each line (positions start at 0, so the line number is i + 1):
def make_index(lines):
index = {}
for i, line in enumerate(lines):
for word in line.split():
if word not in index:
index[word] = []
if i + 1 not in index[word]:
index[word].append(i + 1)
return index
Question 23 (hard): write a function#
The cell below defines a small book, lines, and its index, index: the dictionary that Question 22 builds, which maps each word to a list of its line numbers.
Run this cell to assign lines and index.
lines = ['cats sit', 'dogs sit', 'cats sleep', 'dogs sleep', 'cats dream']
index = {'cats': [1, 3, 5], 'sit': [1, 2], 'dogs': [2, 4], 'sleep': [3, 4], 'dream': [5]}
Write a function called find_in_book that takes lines, index and a word, and returns a list of windows: one window for each line where the word appears. A window is a list of tuples. Each tuple is a line number and the line itself, for the line where the word appears and the two lines before it and the two lines after it. At the start and the end of the book, the window is shorter: it holds only the lines that exist. If the word is not in the index, the function returns an empty list. Line numbers start at 1.
Start from this header (replace ... with the body):
def find_in_book(lines, index, word):
...
Examples
print(find_in_book(lines, index, 'dream'))
[[(3, 'cats sleep'), (4, 'dogs sleep'), (5, 'cats dream')]]
print(find_in_book(lines, index, 'cats'))
[[(1, 'cats sit'), (2, 'dogs sit'), (3, 'cats sleep')], [(1, 'cats sit'), (2, 'dogs sit'), (3, 'cats sleep'), (4, 'dogs sleep'), (5, 'cats dream')], [(3, 'cats sleep'), (4, 'dogs sleep'), (5, 'cats dream')]]
print(find_in_book(lines, index, 'fish'))
[]
Answer
For each line number in the index, build the window around it. The window starts two lines before and ends two lines after, clipped to the lines that exist:
def find_in_book(lines, index, word):
if word not in index:
return []
windows = []
for number in index[word]:
start = number - 2
if start < 1:
start = 1
stop = number + 2
if stop > len(lines):
stop = len(lines)
window = []
for n in range(start, stop + 1):
window.append((n, lines[n - 1]))
windows.append(window)
return windows
Then try: print(find_in_book(lines, index, 'dream')).
The same function with max and min for the clipping:
def find_in_book(lines, index, word):
if word not in index:
return []
windows = []
for number in index[word]:
start = max(1, number - 2)
stop = min(len(lines), number + 2)
window = []
for n in range(start, stop + 1):
window.append((n, lines[n - 1]))
windows.append(window)
return windows
Question 24 (hard): write a function#
Write a function called words_on_line that takes an index and a line number, and returns a list of the words that appear on that line. The index is a dictionary like the one Question 22 builds: each key is a word, and its value is a list of the line numbers where the word appears. If no word appears on the line, the function returns an empty list.
Start from this header (replace ... with the body):
def words_on_line(index, number):
...
Examples
print(words_on_line({'cats': [1, 3], 'sit': [1, 2], 'dogs': [2]}, 1))
['cats', 'sit']
print(words_on_line({'cats': [1, 3], 'sit': [1, 2], 'dogs': [2]}, 2))
['sit', 'dogs']
print(words_on_line({'cats': [1, 3], 'sit': [1, 2], 'dogs': [2]}, 4))
[]
Answer
Loop through the items of the dictionary. Each item is a word and its list of line numbers:
def words_on_line(index, number):
words = []
for word, numbers in index.items():
if number in numbers:
words.append(word)
return words
Then try: print(words_on_line({'cats': [1, 3], 'sit': [1, 2], 'dogs': [2]}, 1)).
The same function without items: loop through the keys and look up each value:
def words_on_line(index, number):
words = []
for word in index:
if number in index[word]:
words.append(word)
return words
Question 25 (hard): write a function#
Write a function called find_phrase that takes a list of lines and two words, and returns a list of tuples. Each tuple is a line number and a word number for a place where the two words appear next to each other, in order, on that line. Line numbers and word numbers both start at 1. As in Question 22, the lines hold lowercase words separated by spaces, and line.split() returns a list of the words in line.
Start from this header (replace ... with the body):
def find_phrase(lines, word1, word2):
...
Examples
print(find_phrase(['cats sit still', 'dogs sit', 'cats sit'], 'cats', 'sit'))
[(1, 1), (3, 1)]
print(find_phrase(['cats sit still', 'dogs sit', 'cats sit'], 'sit', 'still'))
[(1, 2)]
print(find_phrase(['cats sit still', 'dogs sit', 'cats sit'], 'dogs', 'cats'))
[]
Answer
Loop through the lines and the positions in each line. A phrase starts at a position where the first word matches and the next word matches the second word. The last word of a line cannot start a phrase, so the loop stops one position early:
def find_phrase(lines, word1, word2):
found = []
for i in range(len(lines)):
words = lines[i].split()
for j in range(len(words) - 1):
if words[j] == word1 and words[j + 1] == word2:
found.append((i + 1, j + 1))
return found
Then try: print(find_phrase(['cats sit still', 'dogs sit', 'cats sit'], 'cats', 'sit')).
Summary and questions by Prof. Y. Rosenthal, based on Think Python: 3rd Edition by Allen B. Downey. Text license: Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International