Python Tuples
Like a list, but immutable — once created, it can't change.
Creating tuples
Python
point = (3, 4)
colors = ("red", "green", "blue")
single = (42,) # MUST have trailing comma for single item
empty = ()
# Parentheses are optional (tuple packing):
coords = 10, 20, 30 # same as (10, 20, 30)
Indexing and slicing — same as lists
Python
point = (3, 7, 12)
point[0] # 3
point[-1] # 12
point[0:2] # (3, 7)
Tuple unpacking
Python
x, y = (3, 4) # x=3, y=4
a, b, c = "abc" # works on any iterable
# Swap without a temp variable (uses tuple under the hood):
x, y = y, x
# Extended unpacking:
first, *rest = (1, 2, 3, 4)
# first = 1, rest = [2, 3, 4]
head, *middle, last = (1, 2, 3, 4, 5)
# head=1, middle=[2,3,4], last=5
Tuples as dictionary keys
Because tuples are immutable and hashable, they can be used as dictionary keys — lists cannot:
Python
locations = {
(40.71, -74.00): "New York",
(51.50, -0.12): "London",
}
namedtuple — readable tuples
Python
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p.y) # 3 4 — access by name, not just index
When to use tuple vs list
| Use list when | Use tuple when |
|---|---|
| Data will change (add/remove items) | Data is fixed (coordinates, RGB, DB row) |
| All items are the same type | Items may be different types (het. record) |
| Semantic order doesn't matter | Position has meaning (first=x, second=y) |
Performance note
Tuples are slightly faster to create and access than lists, and use less memory. For large read-only datasets, prefer tuples. Python also caches small tuples for reuse.