Tuples – Basics, online

Six activities your students do on their own devices. See who's finished, and their scores.

Tuples – Basics in one minute

What students need to know

Python evaluates the right side as a tuple before assigning. Returning x, y is shorthand for returning the tuple (x, y).

Returning multiple values with commas automatically packs them into a tuple. A point (x, y) shouldn't be modified - immutability signals intent and prevents bugs.

Mistakes students make

  • Python can swap in one line: no temp variable needed.
  • Lists can't be dict keys (mutable). Use a tuple.
  • Function returns 3 values but only 2 variables: must match.
  • Need * before rest to capture multiple remaining values.

Discover other journeys with this module

What students will learn in this module

Every question in Module 59

Quick questions

  1. return x, y what does this return?ATwo separate valuesBA tuple (x, y)
  2. a, b = b, a what does this do?ASwaps a and bBSets both to b
  3. Why use tuples for coordinates?ACoordinates shouldn't changeBTuples are faster
  4. d = {(0,0): 'origin'} why use a tuple key?ATuples are hashable (lists aren't)BIt's shorter
  5. result = divmod(17, 5)\nresult is?A3.4B(3, 2) quotient and remainder

Key terms

Students type the meaning of:

  • return a, b
  • a, b = b, a
  • Tuple as dict key
  • *rest

Match the pairs

a, b, c = (1, 2)Match it to what it does
t[0] = 99Match it to what it does
a, b = b, aMatch it to what it does
return x, yMatch it to what it does
(3, 1, 4).index(1)Match it to what it does
max((2, 8, 5))Match it to what it does

Fill in the blanks

  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

Question 1

Aa = 1Bb = 2Ctemp = aDa = bEb = temp

Question 2

Ad = {}Bd[[0, 0]] = 'origin'Cprint('Origin:', d[(0, 0)])Dprint('Done')

Question 3

A# Function returns 3 valuesBname, age = get_user()Cprint('Name:', name)Dprint('Age:', age)

Question 4

A# Capture remaining valuesBfirst, rest = (1, 2, 3, 4)Cprint('First:', first)Dprint('Rest:', rest)

Question 5

A# Unpack a pairBa, b, c = (1, 2)Cprint('a:', a, 'b:', b)Dprint('Done')