1.2.23Introduction to Programming (Python)

Tuples — immutability, use cases

2,114 words10 min readdifficulty · medium2 backlinks

WHAT is a tuple?


WHY does immutability exist? (first-principles reasoning)

Programming languages give us two flavours of collection on purpose:

  1. Lists — when data changes over time (a growing to-do list).
  2. Tuples — when data should not change (a fixed coordinate, a date).

Deriving "why tuples can be dict keys but lists cannot"

A dictionary stores a key by computing a number from it called a hash. The rule is:

equal objects    equal hashes, forever\text{equal objects} \implies \text{equal hashes, forever}

HOW the logic flows (derive it):

  1. A dict finds a key by its hash, then checks equality.
  2. If a key's contents could change, its hash would change too.
  3. Then the dict would "lose" the entry — you'd never find it again.
  4. Therefore Python only allows hashable (effectively immutable) keys.
  5. Tuples (of immutable items) are immutable → hashable → ✅ valid keys.
  6. Lists are mutable → unhashable → ❌ TypeError.
d = {(0, 0): "origin"}     # works
d = {[0, 0]: "origin"}     # TypeError: unhashable type: 'list'

HOW tuples behave — the operations you can and cannot do

Figure — Tuples — immutability, use cases

Worked Examples


Tuple vs List — when to pick which (80/20)

Tuple List
Syntax () []
Mutable? No Yes
Hashable? Yes (if items are) No
Speed Slightly faster/leaner More overhead
Methods count, index many (append…)

Active Recall

Recall Forecast-then-Verify (predict before you read the answer)
  1. What does type((5)) print? → <class 'int'> (no comma ⇒ not a tuple).
  2. Can (1, [2]) be a dict key? → No — it contains a list, so it's unhashable.
  3. Does t + (1,) modify t? → No — builds a new tuple.
  4. What two methods do tuples have? → count and index.
Recall Feynman: explain to a 12-year-old

Imagine a row of glued-together lockers. You labelled each locker and put a toy inside. Because they're glued, you can't add a new locker or yank one out — that's a tuple: ordered and locked. A list is lockers on wheels you can rearrange anytime. Now, if you put an open box of crayons inside a glued locker, you can't move the locker, but you can still drop more crayons in the box — that's why a tuple holding a list can still have that list changed.


Connections

  • Lists — mutability, methods — the mutable counterpart; choose between them.
  • Dictionaries — keys and values — tuples shine as immutable keys.
  • Sets — hashing & uniqueness — only hashable (tuple-like) items allowed.
  • Functions — return values — multiple returns are really tuples.
  • Mutable vs Immutable objects — the parent concept (int, str, tuple vs list, dict, set).
  • Hashing in Pythonwhy immutability enables dict keys.

What syntactically defines a tuple — parentheses or the comma?
The comma; parentheses are optional grouping. 3, 4 is a tuple, (3) is just an int.
How do you write a one-element tuple?
With a trailing comma: (42,).
Why can tuples be dictionary keys but lists cannot?
Tuples are immutable → hashable (stable hash), lists are mutable → unhashable, so they'd break the dict's lookup.
What error do you get from t[0] = 5 on a tuple?
TypeError — tuples don't support item assignment.
Is tuple immutability deep or shallow?
Shallow — the slots are fixed, but a mutable object stored inside (e.g. a list) can still be modified.
Name the only two tuple methods.
count and index.
Does t = t + (9,) mutate the original tuple?
No — it creates a new tuple and rebinds the name t.
How does swapping a, b = b, a work internally?
The right side b, a is packed into a temporary tuple, then unpacked into a and b.
When should you prefer a tuple over a list (80/20 rule)?
For fixed records, dict/set keys, and data that must not change accidentally.
What does a function return min(x), max(x) actually return?
A tuple (min, max) that the caller can unpack.

Concept Map

builds

has property

contrasts with

enables

permits

unhashable so

allows

conveys

permits only

slicing yields

Tuple ordered collection

The comma

Immutability

List mutable

Hashable value

Valid dict key or set member

Safe to share

Signals intent

Read-only ops index slice len

New tuple on slice or concat

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Socho tuple ek sealed envelope hai aur list ek open box. Tuple ko () aur commas se banate hain — par yaad rakho asli cheez comma hai, parentheses nahi. (3) toh sirf integer 3 hai, lekin (3,) ek tuple hai. Tuple ke andar items ka order fixed hota hai aur ek baar bana lo toh tum unhe change, add ya delete nahi kar sakte — isi ko immutability kehte hain. List me ye sab allowed hai.

Immutability ka faayda kya hai? Kyunki tuple kabhi badalta nahi, isko dictionary ki key ya set ka element banaya ja sakta hai. Reason simple hai: dict key ko hash number se dhoondhta hai, aur agar value badal jaaye toh hash bhi badal jaayega aur entry kho jaayegi. Isliye Python sirf immutable (hashable) cheezon ko key banane deta hai — tuple chalega, list TypeError degi. Grid ya coordinates (x, y) store karne ke liye tuple perfect hai.

Ek important trap: immutability shallow hoti hai. Agar tuple ke andar ek list rakhi hai, jaise t = (1, [2, 3]), toh t[1].append(4) chal jaayega! Slot fixed hai, lekin slot jis list ko point kar raha hai woh badal sakti hai. Lekin t[1] = [9] phir bhi error dega.

Practical use: functions se ek saath multiple values return karna (return min, max) actually tuple hi hota hai, aur a, b = b, a se variable swap bhi tuple packing-unpacking se hota hai. Rule of thumb (80/20): fixed record ya key chahiye → tuple; data badalta rahega → list.

Go deeper — visual, from zero

Test yourself — Introduction to Programming (Python)

Connections