Tuples: Packing & Unpacking
Tuples are not just "immutable lists". They are structurally different. While lists are for collections of the same type, tuples are for records of different types with a fixed structure.
A common interview question is: "What is the difference between a list and a tuple?"The junior answer is: "Tuples are immutable." The senior answer is: "Lists are for homogeneous sequences. Tuples are for heterogeneous structures."
What You'll Learn
- The Philosophy: Why
(x, y)is a tuple but[x, y]is a list. - Internals: How Single-Block Allocation makes tuples faster and lighter.
- Unpacking: The art of
a, b = b, aand star expressions*rest. - NamedTuples: Creating readable records without full Classes.
Memory Internals: Single-Block Allocation
Lists need two blocks of memory: the list object itself and the separate array of pointers (because it needs to resize). Tuples, being immutable, are allocated as a single block of memory.
import sys
l = [1, 2, 3]
t = (1, 2, 3)
# Lists carry "Growth Room" baggage
print(sys.getsizeof(l)) # ~88 bytes
# Tuples are perfectly sized
print(sys.getsizeof(t)) # ~64 bytes (Significant savings at scale!)The Art of Unpacking
Tuple unpacking (or destructuring) is one of Python's most beautiful features. It allows you to assign multiple variables at once.
1. The Swap
No temp variables needed.
a = 10
b = 20
a, b = b, a # Swapped!2. The Star (Extended Unpacking)
Capture the "rest" of the items.
data = (1, 2, 3, 4, 5, 6)
first, *middle, last = data
print(first) # 1
print(middle) # [2, 3, 4, 5] (Note: The 'rest' becomes a LIST)
print(last) # 63. Ignoring Values
Use _ (underscore) for values you don't need.
person = ("Rohit", 30, "Engineer", "New York")
name, _, role, _ = person
# We only cared about name and roleNamedTuples: Self-Documenting Code
Standard tuples have a weakness: you access data by index p[0], which is unreadable. If you don't want to write a full Class, use collections.namedtuple.
from collections import namedtuple
# ⌠The Mystery Tuple
# What is 255? What is 0?
color = (255, 0, 0)
# ✅ The Named Tuple
Color = namedtuple("Color", ["red", "green", "blue"])
red = Color(255, 0, 0)
print(red.red) # 255 (Access by name!)
print(red[0]) # 255 (Still works by index)
print(red) # Color(red=255, green=0, blue=0) (Nice repr)When to use Tuples?
✅ Use Tuples When...
- Data represents a fixed record (e.g., coordinates
x, y). - You want to use the data as a Dictionary Key (Lists can't be keys!).
- You are returning multiple values from a function.
⌠Use Lists When...
- The data needs to grow or shrink.
- The collection is homogeneous (e.g., a list of filenames).