Tuples — Immutable Sequences & Unpacking
BeginnerTuples are immutable, ordered sequences — used for fixed records, multiple return values, dict keys, and elegant unpacking.
Overview
A tuple is a list you cannot change: fixed size, immutable, hashable (if its elements are). That immutability is a feature — tuples communicate "this is a record, not a collection", can serve as dictionary keys ((row, col) coordinates!), and are slightly faster and smaller than lists. Every "multiple return value" in Python is secretly a tuple, and tuple unpacking is the idiom behind swap, enumerate and dict.items() loops.
Tuples as Records & Dict Keys
Parentheses are optional — commas make the tuple. A one-element tuple needs a trailing comma: (5,). Since tuples hash, they unlock coordinate keys and multi-field grouping.
point = (3, 4)
person = "Asha", 24, "Pune" # parens optional
single = (5,) # comma makes it a tuple!
x, y = point # unpacking
name, age, city = person
# Tuples as dict keys — grid problems!
visited = {}
visited[(0, 0)] = True
visited[(2, 3)] = True
print((2, 3) in visited) # True — O(1)
# Immutable = safe to share
# point[0] = 99 -> TypeError
# but: a tuple holding a LIST allows mutating the list
t = (1, [2, 3])
t[1].append(4) # legal! tuple holds same list ref
print(t) # (1, [2, 3, 4])namedtuple — Readable Records
collections.namedtuple gives tuple fields names, so code reads student.cgpa instead of student[2] — with zero memory overhead vs a plain tuple. (dataclasses, covered later, are the mutable big sibling.)
from collections import namedtuple
Student = namedtuple("Student", ["name", "roll", "cgpa"])
s = Student("Vikram", 41, 9.1)
print(s.name, s.cgpa) # Vikram 9.1 — readable
print(s[2]) # 9.1 — still a tuple
name, roll, cgpa = s # still unpacks
# Sorting records stays clean
students = [Student("Asha", 12, 8.7), Student("Neha", 7, 9.4)]
top = max(students, key=lambda st: st.cgpa)
print(top.name) # NehaKey Points to Remember
- 1Tuples are immutable and hashable — usable as dict/set keys (lists are not)
- 2(5,) is a tuple; (5) is just the int 5 — the comma matters
- 3return a, b returns a tuple; unpacking works everywhere (loops, swaps, star-unpacking)
- 4Immutability is shallow — a tuple containing a list allows the list to change
Interview Questions
Sign in to ask AriaWhy can a tuple be a dict key but a list cannot?
A tuple contains a list — can you modify that list? Explain shallow immutability.
Ask Aria about Tuples — Immutable Sequences & Unpacking
Your personal AI tutor — ask anything about this concept
Revision Status
Personal Notes
Sign in to save personal notes for this topic.
Discussion
Sign in to join the discussion.