MOD-10 · Sequence #10 · Python Collections

Python Tuples

Tuples are ordered, immutable sequences. Because they cannot be modified after creation, tuples have a smaller memory footprint than lists, can be hashed as dictionary keys, and support structural packing and unpacking.

Live Interactive Code Snippet (Python 3.12 CPython WASM) Open in Practice Mode →
thistuple = ("apple", "banana", "cherry")
a, *rest = thistuple
print(a, rest)  # 'apple', ['banana', 'cherry']

Core Principles & Mental Models

1. Tuples as Immutable Records

Fixed Structure and Memory Efficiency

  • Tuples represent heterogeneous records of fixed length (e.g., coordinates (x, y, z), database rows).
  • CPython optimizes tuples: because they cannot grow, there is no over-allocation buffer, reducing memory overhead.
  • Single-element tuples require a trailing comma: `single = (42,)`. Without the comma, `(42)` is just parenthesized integer 42.
point = (10, 20, 30)
# point[0] = 15 -> TypeError: 'tuple' object does not support item assignment
print("Tuple:", point)
💡 Key Takeaway: Use tuples for data that should remain constant throughout execution.

2. Extended Unpacking (*rest)

Capturing Variable-Length Slices

  • Python allows capturing remaining elements into a list using the star operator: `head, *tail = iterable`.
  • Can be used anywhere in the pattern: `first, *middle, last = numbers`.
scores = [100, 95, 88, 72, 60]
highest, *other_scores, lowest = scores
print(f"Highest: {highest}, Lowest: {lowest}, Middle count: {len(other_scores)}")
💡 Key Takeaway: Extended unpacking simplifies extracting subsets of ordered data cleanly.

Interactive Walkthrough Examples

Tuples as Dictionary Keys (Hashability) (Basic)

Using coordinates as dictionary keys (which fails for mutable lists).

grid_lookup = {
    (0, 0): "Origin",
    (1, 0): "East",
    (0, 1): "North"
}
target = (1, 0)
print(f"Location at {target}: {grid_lookup[target]}")

Explanation: Because tuples of hashable items are immutable, they implement __hash__ and can serve as dictionary keys.

Common Misconceptions & Exam Traps

Common Pitfall: Tuples Containing Mutable Objects (Shallow Immutability)

A tuple only guarantees that its pointers cannot be reassigned. If an element points to a mutable list, that list can still be mutated.

Buggy Code
t = (1, 2, [10, 20])
t[2].append(30)  # Mutates the inner list successfully!
print("t:", t)  # (1, 2, [10, 20, 30])
# hash(t) -> TypeError: unhashable type: 'list'
Correct Solution
t = (1, 2, (10, 20))  # Use nested tuples for complete immutability
print("Hashable tuple:", hash(t))

Exam Trap Note: Exams love testing if `(1, [2])` can be a dictionary key. It raises TypeError because it contains an unhashable list.

Conceptual Knowledge Self-Check Quiz

Q1: What is the type of the expression `x = (5)` in Python?

  1. tuple
  2. int
  3. generator
  4. set

Without a trailing comma, parentheses are treated as an arithmetic grouping operator. `(5,)` is a tuple; `(5)` is an integer.

Algorithmic Practice Challenges

Idiomatic Best Practices

  • ✅ Always include the trailing comma for single-element tuples: `(val,)`.
  • ✅ Use typing.NamedTuple or dataclasses for structured records with named fields.

All 26 Curriculum Modules