Beginner · Lesson 23 of 94

Tuples, unpacking, and sets

Watch this lesson

View full playlist ↗

Read the lesson

What you'll learn

Concept

A tuple is an immutable sequence. You write it with commas, usually inside parentheses: ("London", 51.5, -0.12). It indexes and slices like a list, but you cannot append to it or assign to an index. That sounds like a list with features removed, and it is, on purpose. A tuple says "this is a fixed record": a coordinate, a date as year-month-day, a database row. The positions have meaning, and the length never changes.

Tuples, unpacking, and sets: list: many items of one kind; ['ada', 'grace', 'linus' → tuple: one record with fixed slots; ('London', 51.5, -0.12)
Tuples, unpacking, and sets · Figure 1 · Open for full size

Unpacking is the reason tuples feel natural. city, lat, lon = record assigns all three names in one line. You have used it already with for key, value in d.items() and with functions that return two values. A star catches the rest: first, *others = scores puts the first item in first and everything else in a list. And a, b = b, a swaps two variables without a temporary, because the right side builds a tuple before the left side is assigned.

Statement Result
x, y = (1, 2) x = 1, y = 2
x, y = y, x swap
first, *rest = [1, 2, 3] first = 1, rest = [2, 3]
*init, last = [1, 2, 3] init = [1, 2], last = 3
a, (b, c) = 1, (2, 3) nested unpacking: b = 2, c = 3

Because tuples are immutable they can be dictionary keys and set members, which lists cannot. That makes (row, col) the standard key for a grid, and (year, month) a natural key for grouping by month. One quirk: a tuple of one item needs a trailing comma, (5,), because (5) is only the number five in parentheses.

A set is an unordered collection of unique items. Add the same value twice and it is there once. Membership tests with in are instant regardless of size, unlike a list, which checks every item. Use a set when the question is "have I seen this?" or "which items are in both?". Write one with braces, {"a", "b"}, or set(some_list) to de-duplicate a list; {} alone is an empty dictionary, so an empty set is set().

Tuples, unpacking, and sets: a = {1, 2, 3} → a | b: {1, 2, 3, 4} → b = {3, 4} → a & b: {3} → a - b: {1, 2}
Tuples, unpacking, and sets · Figure 2 · Open for full size

Code

Tuples as records, with indexing, unpacking, and the immutability that defines them.

# records.py
capital = ("London", 51.5, -0.12)
city, lat, lon = capital

print(capital[0], len(capital))
print(f"{city} is at {lat}, {lon}")
print(type((5,)), type((5)))
capital[0] = "Paris"
Output
London 3
London is at 51.5, -0.12
<class 'tuple'> <class 'int'>
Traceback (most recent call last):
  File "records.py", line 7, in <module>
    capital[0] = "Paris"
    ~~~~~~~^^^
TypeError: 'tuple' object does not support item assignment

Unpacking patterns: swap, star, and the loop form you already know.

# unpack.py
a, b = 1, 2
a, b = b, a
print(a, b)

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

for name, score in [("ada", 91), ("linus", 67)]:
    print(f"{name}: {score}")
Output
2 1
10 [20, 30, 40]
[10, 20, 30] 40
ada: 91
linus: 67

Tuples as dictionary keys: a grid keyed by (row, col). A list key would raise a TypeError; a tuple key works because it cannot change.

# grid_keys.py
board = {}
board[(0, 0)] = "X"
board[(1, 1)] = "O"
board[(0, 0)] = "X"

print(board)
print((1, 1) in board, (2, 2) in board)
print(board.get((2, 2), "."))
Output
{(0, 0): 'X', (1, 1): 'O'}
True False
.

Sets: de-duplicating, membership, and the three operations. Printing a set shows its items in an arbitrary order, so the sets are sorted here for a stable display.

# sets.py
visits = ["ada", "linus", "ada", "grace", "linus", "ada"]
unique = set(visits)

print(len(visits), len(unique))
print(sorted(unique))
print("grace" in unique, "guido" in unique)

python_devs = {"ada", "grace", "linus"}
web_devs = {"linus", "guido"}
print(sorted(python_devs | web_devs))
print(sorted(python_devs & web_devs))
print(sorted(python_devs - web_devs))
Output
6 3
['ada', 'grace', 'linus']
True False
['ada', 'grace', 'guido', 'linus']
['linus']
['ada', 'grace']

Try it yourself

Create attendance.py with two lists of names: people who came on Monday and people who came on Tuesday, with some overlap and some duplicates. Use sets to print who came both days, who came only on Monday, and how many distinct people came in total. Then store each person's best score as a dictionary keyed by (name, day) tuples and print one entry by its tuple key.

Common mistakes

What's next

You have all four core collections. Next you will go deeper into the one that carries most real data: the dictionary.

Course overview