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.
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 [...]:
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!
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?
| Feature | list ([1, 2, 3]) | tuple ((1, 2, 3)) |
|---|---|---|
| Mutable? | Yes (.append(), .pop()) | No (locked after creation) |
| Use case | Growing collections of similar items (users, tasks) | Fixed-structure records ((lat, lng), (name, age)) |
| Memory & Speed | Slightly 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 *:
# 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!
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
Quick Quiz: Module 4.2 — Tuples & Unpacking
Keep Exploring: Related Lessons & Tools
All Courses →Validate, prettify, minify, sort keys, explore interactive collapsible JSON trees, and generate TypeScript interfaces instantly.
Convert Unix epoch seconds/milliseconds to ISO-8601 and local timezones, and bulk-generate UUID v4, time-ordered UUID v7, and sortable ULIDs.