Python · Module 04: Built-In Data StructuresTutorial 10 of 30

4.2 Tuples, Packing, Star-Unpacking & NamedTuples

Learn why Python has tuples alongside lists: fixed records, faster memory footprint, dictionary keys, clean star-unpacking, and readable NamedTuples.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. What Is a Tuple? (The Sealed Envelope Analogy)

A tuple is an ordered collection just like a list — except it is immutable (sealed in an envelope) the moment you create it. You use parentheses (...) instead of square brackets [...]:

PYTHON
point = (10, 20)        # (x, y) coordinate — fixed record!
rgb   = (255, 128, 0)   # Color tuple

print(point[0])         # 10
# point[0] = 99         # ✗ TypeError: 'tuple' object does not support item assignment

The #1 Tuple Syntax Trap: A 1-Item Tuple MUST Have a Trailing Comma!

PYTHON
not_a_tuple = (42)      # int! Parentheses alone just group math expressions
is_a_tuple  = (42,)     # ✓ tuple! The trailing comma makes it a tuple

print(type(not_a_tuple))  # <class 'int'>
print(type(is_a_tuple))   # <class 'tuple'>

2. When Should You Use a Tuple Instead of a List?

Featurelist ([1, 2, 3])tuple ((1, 2, 3))
Mutable?Yes (.append(), .pop())No (locked after creation)
Use caseGrowing collections of similar items (users, tasks)Fixed-structure records ((lat, lng), (name, age))
Memory & SpeedSlightly larger (allocates spare capacity)Smaller & slightly faster to create
Usable as a dict key / in a set?✗ No (TypeError: unhashable)✓ Yes! (if all elements inside are immutable)

3. Packing & Star-Unpacking (*rest)

Python's tuple unpacking makes code remarkably clean. You can even capture "everything in between" using a single star *:

Visual: Tuple Star-Unpacking (`first, *middle, last = (10, 20, 30, 40, 50)`)
1020304050first10 (int)*middle[20, 30, 40] (list)last50 (int)
PYTHON
# 1) Returning multiple values from a function (actually returns a tuple!)
def min_max(nums):
    return min(nums), max(nums)

low, high = min_max([8, 2, 15, 4])
print(low, high)          # 2 15

# 2) Star unpacking (*middle always becomes a list)
first, *middle, last = (10, 20, 30, 40, 50)
print(first)              # 10
print(middle)             # [20, 30, 40]
print(last)               # 50

# 3) Ignoring unwanted values with underscore _
host, _, port = ("localhost", "tcp", 5432)

4. Level Up: NamedTuple (Readable Records with Zero Overhead)

Accessing user[0] and user[2] can get cryptic. Python's standard library gives you NamedTuple — it behaves like a lightweight tuple and lets you access fields by name!

PYTHON
from typing import NamedTuple

class Point(NamedTuple):
    x: int
    y: int

p = Point(10, 25)
print(p.x, p.y)      # 10 25 (Readable!)
print(p[0], p[1])    # 10 25 (Still works like a tuple!)

5. Interactive Trace: Unpacking & Ignoring Values

Tracing Tuple Packing & Star-Unpacking
Interactive Line-by-Line Execution Trace · Step 1 of 4
1→record = ("Riya", 91, 88, 95, "India")
2name, *scores, country = record
3avg = sum(scores) / len(scores)
4print(f"{name} ({country}): {avg:.1f}")
Variables in Memory
record("Riya", 91, 88, 95, "India")tuple
Console Output
(nothing printed yet)
What just happened: Packs 5 values into one immutable tuple record.

Quick Quiz: Module 4.2 — Tuples & Unpacking

Q1.What is `type((5))` in Python?
Q2.After `a, *b, c = (1, 2, 3, 4)`, what is `b`?
Q3.Why can `(10, 20)` be used as a dictionary key, whereas `[10, 20]` cannot?

Keep Exploring: Related Lessons & Tools

All Courses →