Sub topic 2
Tuples as Dictionary Keys and Set Members
Assume you know basic Python syntax, lists, indexing, functions, and for loops.
A tuple is an ordered sequence that cannot be rebound after creation. If every item in a tuple is hashable, Python can use the tuple as a dictionary key or set member. Hashable objects have a stable hash value, so Python can find them efficiently.
locations = {
(40.7128, -74.0060): "New York",
(51.5074, -0.1278): "London",
}
print(locations[(51.5074, -0.1278)])
visited = {(0, 0), (1, 0)}
visited.add((1, 1))
print(visited)A tuple containing a mutable, unhashable object such as a list cannot be used this way.
| Tuple | Can be a key or set member? |
|---|---|
| `(2, 3)` | Yes |
| `("user", 7)` | Yes |
| `([2, 3], 4)` | No |
Packing and Unpacking
Packing puts several values into one tuple. Unpacking assigns the tuple's items to separate names.
point = 3, 4
x, y = point
print(x, y)The number of target names normally must match the number of values.
Multiple Assignment and Swapping Values
Python performs multiple assignment as one operation. This makes swapping names simple and avoids a temporary variable.
left = "red"
right = "blue"
left, right = right, left
print(left, right)The right side is evaluated before the assignments change the names.
Capturing the Rest with Starred Targets
A starred target collects zero or more remaining values into a list. It is useful when one part has a known position but the middle has variable length.
first, *middle, last = [10, 20, 30, 40, 50]
print(first)
print(middle)
print(last)Here, first is 10, middle is [20, 30, 40], and last is 50. Only one starred target is allowed in an unpacking pattern.
Exercise
What happens when a, b = (1, 2, 3) runs, and how could you capture the extra value?
Show answer
It raises ValueError. Use a, b, *rest = (1, 2, 3); then rest is [3].