Tuples, Immutability, and Packing
Key Takeaways
- Tuples are ordered sequences, so they support indexing, slicing, len, iteration, and membership tests.
- Tuples are immutable, so assigning to an element or deleting one element raises TypeError.
- A one-item tuple requires a trailing comma, such as (value,), because parentheses alone do not create a tuple.
- Tuple packing and unpacking let Python group several values and assign them back to names position by position.
- A tuple is hashable only when all of its elements are hashable, which matters when using tuples as dictionary keys.
Tuple basics
A tuple is an ordered sequence. Like a list or string, it supports indexing, negative indexing, slicing, len(), membership with in, and iteration in a for loop. The major difference is immutability: after a tuple is created, its element positions cannot be reassigned, inserted into, or removed from individually.
point = (10, 20, 30)
print(point[0]) # 10
print(point[-1]) # 30
print(point[1:3]) # (20, 30)
Trying to change a tuple element raises TypeError.
point = (10, 20)
point[0] = 99 # TypeError
This does not mean the variable name is frozen. You can reassign the name to a different tuple. The tuple object itself is what cannot be changed.
point = (10, 20)
point = (99, 20) # allowed: name now refers to a new tuple
The comma creates the tuple
A common PCEP trap is the one-item tuple. Parentheses are often used for grouping expressions, so (5) is just the integer 5. The trailing comma makes a tuple.
| Expression | Type idea |
|---|---|
(5) | Integer expression grouped by parentheses |
(5,) | One-item tuple |
5, | One-item tuple without parentheses |
(5, 6) | Two-item tuple |
When reading code, look for the comma before assuming a value is a tuple.
Packing and unpacking
Tuple packing happens when Python gathers values into a tuple. Unpacking assigns elements from a tuple or other iterable into separate names.
record = 'Ada', 36, 'Python' # packing
name, age, language = record # unpacking
print(name) # Ada
The number of target names must match the number of values unless starred unpacking is used. PCEP usually tests the simple rule: two names require exactly two values, three names require exactly three values.
x, y = (1, 2) # works
x, y = (1, 2, 3) # ValueError
A useful unpacking pattern is swapping values without a temporary variable:
left = 'L'
right = 'R'
left, right = right, left
Python evaluates the right side first, packs those values, then unpacks them into the left-side names.
Immutable tuple, mutable contents
Tuple immutability applies to the tuple positions, not necessarily to the objects inside them. A tuple can contain a list. You cannot replace the list at that tuple position, but you can mutate the list itself.
box = ([1, 2], 'ok')
box[0].append(3)
print(box) # ([1, 2, 3], 'ok')
That distinction matters for dictionary keys and set elements. A tuple can be hashable only if every element inside it is hashable. (1, 2) can be a dictionary key. ([1, 2], 3) cannot, because the list inside it is mutable and unhashable.
Tuple methods and use cases
Tuples have fewer methods than lists. The common ones are count(value) and index(value). Use tuples when the structure should be fixed, such as a coordinate, a small record, or multiple values returned from a function. Use lists when the collection is meant to grow, shrink, or be reordered.
Which expression creates a tuple containing exactly one integer?
What happens when this code runs? t = (1, 2); t[0] = 9
Which value can be used as a dictionary key because it is hashable?