Python Fundamentals ยท Collections

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.

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.