Skip to content
Codewilds

Lesson 16 of 34 · Lists & Tuples

Python Tuples and Unpacking

medium20 XP3 min read

A tuple is an ordered sequence just like a list — except that it can't be changed after it's created. That makes tuples perfect for small, fixed groups of values: coordinates, RGB colours, a name with a score. Paired with unpacking, they let you return several values from a function and pull data apart in one elegant line.

Creating tuples

Tuples are written with commas, usually inside parentheses:

point = (3, 4)
color = (255, 128, 0)
hero = ("Ada", 98)
single = (5,)        # one-item tuple: the comma is required!
not_a_tuple = (5)    # just the number 5 in parentheses
empty = ()

In fact it's the comma that makes a tuple — point = 3, 4 works too. Indexing, slicing, len(), in and looping all work exactly like they do for lists.

Tuples are immutable

point = (3, 4)
point[0] = 10   # TypeError: 'tuple' object does not support item assignment

Immutability is a feature: a tuple can be shared safely without anyone changing it behind your back, and because it can't change, it can be used as a dictionary key or stored in a set (Chapter 4).

Returning multiple values

When a function returns several values separated by commas, it actually returns one tuple:

def divide(a, b):
    return a // b, a % b


result = divide(17, 5)
print(result)             # (3, 2)
quotient, remainder = divide(17, 5)
print(quotient)           # 3

Unpacking

Unpacking assigns the items of a sequence to several variables at once. The number of variables must match the number of items:

x, y = (3, 4)
name, score = ["Ada", 98]     # works with lists too
a, b, c = "hey"               # and strings: 'h', 'e', 'y'

It also gives you Python's famous one-line swap — no temporary variable needed:

a, b = 1, 2
a, b = b, a
print(a, b)   # 2 1

Star unpacking

A variable prefixed with * collects "everything else" into a list:

first, *rest = [10, 20, 30, 40]
print(first, rest)          # 10 [20, 30, 40]

*init, last = [10, 20, 30, 40]
print(init, last)           # [10, 20, 30] 40

head, *middle, tail = "a b c d".split()
print(middle)               # ['b', 'c']

If there's nothing left to collect, the starred variable is simply an empty list.

Unpacking in for loops

Lists of tuples are everywhere, and unpacking in the loop header keeps the code readable:

results = [("Ada", 98), ("Bo", 75)]
for name, score in results:
    print(f"{name}: {score}")

Use _ for values you don't need: for _, score in results:.

Tuples versus lists

Use a list for a collection of similar items that may grow or change (a party of heroes). Use a tuple for a fixed record whose positions mean different things (one hero's name and score). Tuples compare item by item, from left to right — ("Ada", 98) < ("Bo", 75) is True because "Ada" < "Bo" — which makes them handy for sorting.

Common mistakes

  • (5) is not a tuple — write (5,).
  • Trying to modify a tuple raises TypeError; build a new tuple instead.
  • Unpacking the wrong number of items raises ValueError: too many values to unpack or not enough values to unpack. Star unpacking helps when the length varies.

Assignment

Write three functions:

  1. min_max(numbers) returns a tuple (smallest, largest) for a non-empty list of numbers.
  2. split_name(full_name) returns a tuple (first, last) with the first and last words of a name, ignoring middle names and extra spaces. A one-word name returns (name, "").
  3. swap_pairs(pairs) takes a list of 2-item tuples and returns a new list with the two items of every tuple swapped.
min_max([3, 9, 1, 7])                 # (1, 9)
split_name("Ada King Lovelace")       # ("Ada", "Lovelace")
split_name("Plato")                   # ("Plato", "")
swap_pairs([(1, "a"), (2, "b")])      # [("a", 1), ("b", 2)]

Premium lesson

Unlock the full Learn Python course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Destructuring and multiple values in other languages

Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.

Lesson last updated on .

Write code ↓
Python+20 XP

Lesson 16 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn Python course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.