Tuples – Basics

Tip: Choose Save as PDF in the print dialog to download. Use A4 paper size.

Tuples – Basics

Name:
Date:
Class:

Quick Questions

Shade in the A or B circle for each question.

1. return x, y what does this return?
A Two separate values
B A tuple (x, y)
2. a, b = b, a what does this do?
A Swaps a and b
B Sets both to b
3. Why use tuples for coordinates?
A Coordinates shouldn't change
B Tuples are faster
4. d = {(0,0): 'origin'} why use a tuple key?
A Tuples are hashable (lists aren't)
B It's shorter
5. result = divmod(17, 5)\nresult is?
A 3.4
B (3, 2) quotient and remainder

Match the Pairs

Draw a line connecting each item on the left to its match on the right.

Left columnRight column
1a, b, c = (1, 2) AOutput: 1
2t[0] = 99 BOutput: 8
3a, b = b, a CError: Not enough values to unpack
4return x, y DError: Cannot modify tuple items
5(3, 1, 4).index(1) EOk: Return multiple values as a tuple
6max((2, 8, 5)) FValid: Swap two values with tuple unpacking

Definitions

return a, b

Fill in the Blanks

Complete each line of code by filling in the missing parts.

1.
def min_max(nums): ______ min(nums), max(nums)
2.
a, b = _, a # swap
3.
grid = {} grid[_____] = 'start'
4.
first, _____ = (1, 2, 3, 4)
5.
_, value = ('key', 42)

Spot the Error

Shade in the letter of the line that contains an error.

Question 1
A a = 1
B b = 2
C temp = a
D a = b
E b = temp
Question 2
A d = {}
B d[[0, 0]] = 'origin'
C print('Origin:', d[(0, 0)])
D print('Done')
Question 3
A # Function returns 3 values
B name, age = get_user()
C print('Name:', name)
D print('Age:', age)
Question 4
A # Capture remaining values
B first, rest = (1, 2, 3, 4)
C print('First:', first)
D print('Rest:', rest)
Question 5
A # Unpack a pair
B a, b, c = (1, 2)
C print('a:', a, 'b:', b)
D print('Done')

Answer Key

Tuples – Basics
Section A: Quick Questions
Q1
B — A tuple (x, y)
Q2
A — Swaps a and b
Q3
A — Coordinates shouldn't change
Q4
A — Tuples are hashable (lists aren't)
Q5
B — (3, 2) quotient and remainder
Section B: Match the Pairs
Q1
a, b, c = (1, 2) → Error: Not enough values to unpack
Q2
t[0] = 99 → Error: Cannot modify tuple items
Q3
a, b = b, a → Valid: Swap two values with tuple unpacking
Q4
return x, y → Ok: Return multiple values as a tuple
Q5
(3, 1, 4).index(1) → Output: 1
Q6
max((2, 8, 5)) → Output: 8
Section C: Definitions
Q1
return a, b — Returns multiple values from a function as a tuple.~~a, b = b, a
Section D: Fill in the Blanks
Q1
def min_max(nums): return min(nums), max(nums)
Q2
a, b = b, a # swap
Q3
grid = {} grid[(0,0)] = 'start'
Q4
first, *rest = (1, 2, 3, 4)
Q5
_, value = ('key', 42)
Section E: Spot the Error
Q1
C — Python can swap in one line: no temp variable needed
Q2
B — Lists can't be dict keys (mutable). Use a tuple.
Q3
B — Function returns 3 values but only 2 variables: must match
Q4
B — Need * before rest to capture multiple remaining values
Q5
B — 3 variables but only 2 values: ValueError