Strings & Data Structures
Tuples
Complete lesson for Tuples using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.
Basics — Tuples
Section: Strings & Data Structures. Python tuples: immutable ordered sequences — packing, unpacking, single-element commas, and when to choose tuple over list.
What is a tuple?
- A tuple is an ordered, immutable sequence. Write it with parentheses:
(1, 2, 3). - Parentheses are often optional in assignments:
t = 1, 2, 3still makes a tuple. - Tuples can hold mixed types and nested tuples.
- Real life: fixed records like (latitude, longitude), RGB
(r, g, b), or a function returning multiple values.
point = (3, 4)
print(point, type(point).__name__, len(point))
# Output:
# (3, 4) tuple 2 Immutability rules
- You cannot assign to an index:
t[0] = 9raisesTypeError. - You cannot
append/remove. Build a new tuple with concatenation if needed. - If a tuple contains a mutable object (e.g. a list), that inner object can still change.
- Immutability of the tuple structure ≠ deep freeze of nested mutables.
t = (1, [2, 3])
t[1].append(4)
print(t)
# Output:
# (1, [2, 3, 4]) Single-element and empty tuples
- Empty tuple:
()ortuple(). - Single-element tuple needs a trailing comma:
(5,)—(5)is just the int 5. - This comma rule is a classic beginner/interview gotcha.
tuple("ab")→("a", "b")because strings are iterable.
print(type((5)).__name__)
print(type((5,)).__name__)
# Output:
# int
# tuple Indexing, slicing, and operators
- Indexing/slicing work like lists/strings:
t[0],t[-1],t[1:3]. +concatenates tuples;*repeats:(1, 2) * 2→(1, 2, 1, 2).intests membership.len,min,max,sumwork when types allow.- Slicing a tuple returns a new tuple.
t = (10, 20, 30, 40)
print(t[1:3], t + (50,), t * 2)
# Output:
# (20, 30) (10, 20, 30, 40, 50) (10, 20, 30, 40, 10, 20, 30, 40) Built-in functions that work on tuples
- These are **built-in functions** (not tuple methods). Call them as
len(t), nott.len(). sorted(t)returns a **list**. Convert back withtuple(sorted(t))if you need a tuple again.
| Function | What it does | Example | Result |
|---|---|---|---|
len(t) | Number of elements | len((10, 20, 30)) | 3 |
tuple(iterable) | Build a tuple from an iterable | tuple([1, 2]) | (1, 2) |
list(t) | Convert tuple → list (mutable copy of items) | list((1, 2)) | [1, 2] |
sorted(t) | New sorted **list** | sorted((3, 1, 2)) | [1, 2, 3] |
reversed(t) | Reverse iterator | tuple(reversed((1, 2))) | (2, 1) |
min(t) / max(t) | Smallest / largest element | min((3, 1, 2)) | 1 |
sum(t) | Sum of numbers | sum((1, 2, 3)) | 6 |
any(t) / all(t) | Truthy checks across items | all((1, 2, 3)) | True |
enumerate(t) | Index + value pairs | list(enumerate(("a", "b"))) | [(0, "a"), (1, "b")] |
zip(t1, t2) | Pair items from tuples | tuple(zip((1, 2), ("x", "y"))) | ((1, "x"), (2, "y")) |
isinstance(t, tuple) | Type check | isinstance((1,), tuple) | True |
hash(t) | Hash (if all elements hashable) | hash((1, 2)) | an int (usable as dict key) |
Packing and unpacking
- Packing:
t = 1, 2, 3. Unpacking:a, b, c = t(counts must match). - Star unpacking:
first, *rest = tgathers remaining items into a list. - Swap idiom:
a, b = b, auses tuple packing/unpacking. - Functions return multiple values as a tuple:
return x, y.
a, b = 1, 2
a, b = b, a
print(a, b)
first, *mid, last = (1, 2, 3, 4)
print(first, mid, last)
# Output:
# 2 1
# 1 [2, 3] 4 Tuple methods
- Tuples have only **two** methods:
count(x)andindex(x)— immutability keeps the API tiny. - No
append/sortin place. Use built-ins likesorted(t)(returns a list).
| Method | What it does | Example | Result |
|---|---|---|---|
t.count(x) | How many times x appears | (1, 2, 2, 3).count(2) | 2 |
t.index(x) | First index of x | (1, 2, 2, 3).index(3) | 3 (error if missing) |
t.index(x, start, stop) | Search in a range | (1, 2, 3, 2).index(2, 2) | 3 |
x in t | Membership (operator) | 2 in (1, 2, 3) | True |
t + u | Concatenate (new tuple) | (1, 2) + (3,) | (1, 2, 3) |
t * n | Repeat (new tuple) | (1, 2) * 2 | (1, 2, 1, 2) |
t = (1, 2, 2, 3)
print(t.count(2), t.index(3))
# Output:
# 2 3 tuple APIs — overview cheat sheet
- Prefer tuples for fixed records and hashable keys; prefer lists when you need to grow or sort in place.
| Category | Common APIs | Use when |
|---|---|---|
| Built-ins | len, tuple, list, sorted, min, max, sum, enumerate | Measure, convert, aggregate |
| Methods | count, index | Search inside an immutable sequence |
| Operators | +, *, in, unpacking | Combine, repeat, test, destructure |
| Hashing | hash(t) (if elements hashable) | Dict keys / set elements |
Tuples as dict keys and set items
- A tuple is hashable if all of its elements are hashable.
(1, 2)can be a dict key;[1, 2]cannot.(1, [2])is not hashable because of the inner list.- Use tuples for composite keys:
(row, col)→ value.
grid = {(0, 0): "origin", (1, 2): "point"}
print(grid[(1, 2)])
# Output:
# point Tuple vs list — when to choose
- Use a list when the collection will grow, shrink, or be sorted in place.
- Use a tuple for fixed-size records, function multi-returns, and hashable keys.
- Tuples can be slightly more memory-efficient and signal “do not mutate”.
- Many stdlib APIs return tuples (e.g.
enumerate,dict.itemsviews yield pairs).
| Feature | list | tuple |
|---|---|---|
| Mutable | Yes | No |
| Literal | [1, 2] | (1, 2) |
| Methods | Many | count, index |
| Hashable | Never | If elements are |
| Use as dict key | No | Yes (if hashable) |
Advanced — Tuples
namedtuple and alternatives
collections.namedtuplebuilds lightweight immutable records with named fields.- Access by name (
p.x) and index (p[0]). Still a tuple subclass. typing.NamedTupleadds type hints.dataclasseswithfrozen=Trueis a modern alternative.- Prefer named fields over mysterious
row[3]indexes in larger code.
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p[1], p)
# Output:
# 3 4 Point(x=3, y=4) Hashing details
- Hash of a tuple combines hashes of elements — all must be hashable.
- Equal tuples hash equal: required for dict/set correctness.
- Changing a nested mutable after inserting a tuple key breaks the dict — avoid mutable elements in keys.
- Interview phrase: “tuple is immutable and hashable when contents are hashable”.
Performance and intent
- Tuples are often faster to allocate than lists for fixed small records.
- The bigger win is intent: readers know the size/shape should not change.
- Returning a tuple from a function is idiomatic; callers unpack.
- For large growable data, lists (or deques/arrays) remain the right tool.
Tuple pitfalls
- Forgetting the comma in
(5,)creates an int. - Mutating a list inside a tuple surprises people who think “immutable means frozen”.
sorted(t)returns a list — convert back withtuple(sorted(t))if needed.- Unpacking length mismatch raises
ValueError.
Tricky Interview Points
Q1) How do you create a single-element tuple?
Answer Use a trailing comma: (5,) or 5,. Without the comma, (5) is just an integer.
Q2) Are tuples mutable?
Answer The tuple itself is immutable. Contained mutable objects can still be mutated in place.
Q3) Why can tuples be dict keys but lists cannot?
Answer Dict keys must be hashable. Immutable tuples of hashable items are hashable; lists are mutable and unhashable.
Q4) What methods do tuples support?
Answer Only count and index.
Q5) How does unpacking work?
Answer The number of names on the left must match the tuple length, unless you use *rest to capture extras into a list.
Q6) How do you swap two variables in Python?
Answer a, b = b, a using tuple packing/unpacking — no temporary variable needed.
Q7) list vs tuple — one sentence?
Answer Lists are mutable sequences for changing collections; tuples are immutable sequences for fixed records and hashable keys.
Q8) What does tuple([1, 2]) do?
Answer Builds a new tuple (1, 2) from the iterable.
Q9) Can a tuple contain a list?
Answer Yes. The tuple cannot change which objects it holds, but the list object can still be modified.
Q10) What is a namedtuple?
Answer A factory in collections that creates tuple subclasses with named fields for clearer access.
Q11) Does t + (9,) mutate t?
Answer No. It creates a new tuple. Rebind if you need to keep it: t = t + (9,).
Q12) Why do functions return tuples?
Answer To return multiple values at once. Callers unpack: x, y = f().
Simple Programs
Packing and unpacking
record = ("Ada", 36, "Engineer")
name, age, role = record
print(name, age, role)
# Output:
# Ada 36 Engineer Swap variables
a, b = 10, 20
a, b = b, a
print(a, b)
# Output:
# 20 10 Single-element tuple gotcha
x = (7)
y = (7,)
print(type(x).__name__, type(y).__name__)
# Output:
# int tuple Tuple as dict key
dist = {(0, 0): 0, (0, 1): 1, (1, 0): 1}
print(dist[(0, 1)])
print(sorted(dist.keys()))
# Output:
# 1
# [(0, 0), (0, 1), (1, 0)] Star unpacking
t = (1, 2, 3, 4, 5)
head, *body, tail = t
print(head)
print(body)
print(tail)
# Output:
# 1
# [2, 3, 4]
# 5 namedtuple point
from collections import namedtuple
Point = namedtuple("Point", "x y")
p = Point(2, 5)
print(p.x * p.x + p.y * p.y)
# Output:
# 29 Problem Solving Tricks
- Always write
(x,)for a one-element tuple — the comma makes the tuple. - Swap with
a, b = b, ainstead of a temporary. - Use tuples for composite dict keys like
(row, col). - Return multiple values as a tuple; unpack at the call site.
- Convert to list only when you must mutate, then
tuple(...)back if needed. - Remember nested lists inside tuples can still change.
sorted(t)→ list; wrap withtuple(...)for a sorted tuple.- Prefer
namedtuple/NamedTuplewhen positions are meaningful fields. - Parentheses are optional in many packing contexts:
t = 1, 2. - Check hashability before using a tuple as a set element or key.
Practice Programs List
- Create empty, single-element, and multi-element tuples; print their types.
- Unpack a 4-field record into named variables.
- Swap three variables in a rotation:
a, b, c = b, c, a. - Show that mutating a list inside a tuple changes printed content.
- Use a tuple key in a dict for a tic-tac-toe cell.
- Convert a list to a tuple, sort via
sorted, convert back. - Write a function that returns min and max as a tuple.
- Demonstrate
countandindexon a sample tuple. - Use star unpacking to drop the middle elements of a tuple.
- Build a
namedtuplefor a Student and print fields. - Explain with code why
(1, [2])cannot go into aset. - Compare memory intent: rewrite a fixed RGB list as a tuple.