Lesson · Core Collections
Tuples
48 min readTuples
Tuples are immutable sequence objects commonly used for fixed records, multiple return values, and hashable composite keys. Immutability changes both design intent and what Python can safely hash.
Learning goals
- Create tuples with comma syntax, including the one-element form
(42,), and explain why parentheses alone do not make a tuple. - Unpack a tuple into names (
x, y = point) and predict theValueErrorwhen the target count and element count disagree. - Explain why a function that appears to return several values is really returning one tuple.
- Replace a tuple element by constructing a new tuple, and read the
TypeErrorthat item assignment raises. - Decide between a tuple and a list from intent (fixed record versus mutable sequence), including the hashability consequence.
Mental model
The comma, not the parentheses, is what packs a tuple, and the same comma-driven machinery unpacks one. Immutability means a "change" is always a new object: point[0] = 5 raises TypeError, and the replacement path is construction such as (5,) + point[1:]. The payoff is dependability, because the slot layout cannot move under you, and a tuple of hashable values can serve as a key or a set member.
The comma packs, the comma unpacks
immutable means every change is a new object
Mental model
the same mechanism as a compact list
values separated by commas → one tuple object (packing) ↓ unpack: x, y = point names bind to the elements of that one object ↓ need a change? build a NEW tuple; item assignment raises TypeError ↓ every element hashable? the tuple can be a dict key or set member
Core idea
A tuple is a fixed sequence whose job is to hold positional facts together: coordinates, records, and the results of a function that returns several values. The comma packs and unpacks it, immutability keeps the slot layout stable, and hashability (when every element qualifies) is what lets the whole record act as a dictionary key. Choose it over a list when the structure is fixed by meaning rather than when it merely happens to be short.
Creation
Creation in Tuples means constructing a new object with valid initial state. Compare literal syntax, constructors, and factory-style APIs where they exist, and note whether construction copies or reuses existing objects.
Packing and unpacking
Packing collects several comma-separated values into a tuple-like structure; unpacking assigns iterable elements to multiple targets. Both are based on iterable behavior rather than special tuple-only rules.
Immutability
Immutability means the object's logical value cannot be modified in place through its public operations. New results are typically represented by new objects, although the object can still reference other mutable objects.
Single-element tuples
The comma creates a tuple, not the parentheses. A one-element tuple therefore needs a trailing comma, as in (value,).
Returning multiple values
A function that appears to return several comma-separated values actually returns one tuple. The caller often unpacks that tuple immediately.
Comparison
Comparison in Tuples follows type-defined equality or ordering rules. Do not assume unrelated types can be ordered, and remember that equality is distinct from identity.
Hashability conditions
A tuple is hashable only when all values it contains are hashable and its equality behavior remains stable. A tuple that contains a list is therefore not hashable.
Tuple vs list
Use a tuple to signal fixed, value-like positional structure and a list for a mutable sequence that can grow or change. Performance differences are usually secondary to semantics.
Walkthrough
point = (3, 4)packs two integers into one tuple;x, y = pointunpacks that one object, bindingxto 3 andyto 4, so the firstprintshows3 4.single = (42,)is the one-element form: the trailing comma is what creates the tuple, while(42)would just be the integer 42;print(single)shows(42,).record = ("Ada", 36, "London")is a fixed positional record, andrecord[0]reads the first slot, printingAda; there is norecord[0] = ...counterpart, because item assignment on a tuple raisesTypeError.- Predict before running: the three printed lines, and what
print(single)would show if the trailing comma were removed. The comma is the only thing makingsinglea tuple, so removing it prints a plain integer.
Experiments to try
- Remove the comma from
single, then printtype(single)in both versions; record the two types and explain which token did the work. - Unpack with the wrong number of targets:
a, b, c = pointraises aValueErrorwhose message says the tuple has too few values. Fix the target count and confirm the error disappears. - Run
point[0] = 5and read theTypeError; then build the changed value as a new object with(5,) + point[1:]and print both tuples to show the original is untouched. - Put
pointin a dict as a key ({point: "corner"}) and confirm the lookup works; then try a list key and a tuple containing a list, and record which entries raiseTypeError: unhashable type.
Common mistakes
- Writing
(42)as a one-element tuple: parentheses only group an expression, so the value is the int 42; the comma builds the tuple, which is why the correct form is(42,). - Unpacking into the wrong number of targets:
a, b, c = (3, 4)raisesValueErrorat runtime, and the message names whether there were too few or too many values to unpack. - Trying to change one slot in place:
point[0] = 5raisesTypeError, because tuple immutability removes item assignment entirely; the replacement must be a newly constructed tuple. - Assuming every tuple can be hashed: a tuple works as a dict key only when each element is hashable, so
(3, [4])fails while(3, 4)succeeds.
Practice: Easy
- Build
point = (3, 4), unpack it intox, y, and print both names plustype(point). Predict the output, then drop the parentheses around the literal and confirm the value is still a tuple. - Create
single = (42,)and printsingle,type(single), andlen(single). Remove the comma, rerun, and explain each difference. - From
record = ("Ada", 36, "London"), readrecord[0]andrecord[-1]; predict both values before running, then say which index reaches the city without counting.
Practice: Medium
- Write
def min_max(values): return min(values), max(values)and call it on[3, 1, 4]. Printtype(min_max([3, 1, 4]))to show the call returns one tuple, then unpacklow, high = min_max([3, 1, 4])and check both names. - Trigger the unpack mismatch with
a, b, c = (3, 4)and read theValueError; then fix it by changing the target count and confirm the corrected line runs. - Build a modified copy of
recordwith a different age, usingrecord[:1] + (37,) + record[2:]; print both tuples and confirm the original still holds 36.
Practice: Hard
- Model a small lookup as a dict keyed by
(city, year)tuples, for example{("London", 2024): 9.0}, and document why the key must be hashable. Test valid lookups, then attempt a key containing a list and record theTypeError. - Build a failure lab with three entries:
(42)used where a tuple was required, a three-target unpack of a two-element tuple, andrecord[0] = "B"raisingTypeError. For each, record the exact exception and explain the mechanism behind it. - For three scenarios (a coordinate pair, a queue of pending jobs, and a dictionary key built from two strings), choose tuple or list and justify each choice with immutability, expected growth, and hashability.
Lesson checklist
- I can create a one-element tuple and explain the role of the trailing comma.
- I can unpack a tuple into names and predict the
ValueErrorwhen the counts disagree. - I can explain why a tuple "change" means building a new tuple, and what
TypeErrorreports otherwise. - I can say when a tuple qualifies as a dict key and when it does not.
Remember
A tuple groups positional facts behind a comma: `(3, 4)` packs, `x, y = point` unpacks, and both operations come from the comma rather than the parentheses. Immutability turns every edit into construction of a new tuple, which buys stable structure and, when every element is hashable, a usable dictionary key. Reach for a tuple when the shape of the data is fixed, and for a list when the sequence is expected to grow or change.
Interview angles
What is the main purpose of **Creation**?+
Creation in Tuples means constructing a new object with valid initial state. Compare literal syntax, constructors, and factory-style APIs where they exist, and note whether construction copies or reuses existing objects.
What should you pay attention to when using **Packing and unpacking**?+
Packing collects several comma-separated values into a tuple-like structure; unpacking assigns iterable elements to multiple targets. Both are based on iterable behavior rather than special tuple-only rules.
How does **Immutability** fit into this lesson?+
Immutability means the object's logical value cannot be modified in place through its public operations. New results are typically represented by new objects, although the object can still reference other mutable objects.
Why is `(42)` not a one-element tuple?+
Parentheses group an expression, and the comma is what actually builds a tuple, so (42) evaluates to the integer 42. The one-element tuple is (42,), and comparing type((42)) with type((42,)) shows the difference immediately.