Tuples and Unpacking

Tuples are fixed-size, unchangeable groups. Unpack them into names, swap two values in one line, and collect "the rest" with a star.

Python · beginner · 6 min · 7 steps · free

What you'll learn

tuples.py

point = (3, 4)
x, y = point                 # unpacking: one name per item
a, b = 1, 2
a, b = b, a                  # swap without a temporary name
first, *rest = [10, 20, 30, 40]
size = len(point)
print(x, y, a, b, first, rest, size)

Step by step

  1. A tuple: values in round brackets. Unlike a list, it can never change.
  2. Unpacking: the first item goes to x, the second to y.
  3. a is created with the value 1. b is created with the value 2.
  4. Swap! The right side builds the tuple (2, 1) first, then unpacks it into a and b.
  5. A starred name collects everything left over into a list: first = 10, rest = [20, 30, 40].
  6. size is created with the value 2.
  7. Tuples group values; unpacking pulls them apart into names in one line.

Common mistakes

Best practices

Key takeaways

Check yourself

p, q = (5, 9). What is q?

Answer: 9. Items are assigned in order.

a, *b = [1, 2, 3]. What is b?

Answer: [2, 3]. The starred name gets a list of the rest.

·

More in Collections