1.2.23 · D3Introduction to Programming (Python)

Worked examples — Tuples — immutability, use cases

2,506 words11 min readBack to topic

This page is the exhaustive drill for Tuples — immutability, use cases. We will map out every kind of situation a tuple can throw at you — packing, unpacking, the sealed-slot rule, hashability, degenerate cases like the empty and one-element tuple — and then work each one to the end.


The scenario matrix

Below is the full list of case classes this topic can generate. Every worked example is tagged with the cell it fills.

Cell Case class What makes it tricky
A Packing values into a tuple return a, b — no parens, still a tuple
B Unpacking (exact / starred / mismatch) count must match exactly, or use *rest
C Degenerate: empty () and single (x,) the trailing comma; (3) is not a tuple
D Read-only ops build new tuples slice, +, * never mutate the original
E Illegal write → TypeError t[0] = ... on a frozen slot
F Shallow immutability a list inside a tuple can still change
G Hashability: tuple as dict/set key works only if every item is hashable
H Word problem (real-world record) picking tuple vs list from meaning
I Exam twist / limiting behaviour count/index edge cases, ValueError

We now fill A–I with 9 worked examples.


Worked Examples










Which error fires? — a decision you must know cold

The two mistakes people confuse most are the write error and the count/search error. This flow separates them by cause.

What went wrong?

Tried to change a slot

Unpacked wrong number of names

Searched for a value not present

TypeError item assignment

ValueError not enough values

ValueError x not in tuple

Read it as: writing to a frozen tuple is a type sin (TypeError); counting/searching problems are value sins (ValueError). Cells E, B, and I each land on a different leaf.


Active Recall

Recall Predict the type / result

Is p = 3, 4 a tuple, and why? ::: Yes — the top-level comma builds a tuple; parentheses are optional. a, *b, c = (1,2,3,4) — what is b? ::: The list [2, 3] (star target always yields a list). x, y, z = (10, 20) raises what? ::: ValueError: not enough values to unpack — 3 names but 2 values. t[0:2] on t = (1,2,3) returns what, and is t changed? ::: A new tuple (1, 2); t is unchanged (slice is read-only). Can (1, [2]) be a dict key? ::: No — the inner list is unhashable, so the tuple is too. t.index(9) when 9 is absent raises what? ::: ValueError, not TypeError.


Connections

  • Tuples — immutability, use cases — the parent this drill serves.
  • Lists — mutability, methods — the mutable sibling from Cells B, D, F.
  • Dictionaries — keys and values — Cells G and H live here.
  • Sets — hashing & uniqueness — same hashability rule as dict keys.
  • Functions — return values — packing/unpacking of Cell A.
  • Mutable vs Immutable objects — the concept behind Cells E and F.
  • Hashing in Pythonwhy Cell G behaves as it does.