Tuples & Immutability
Tuples are like lists but immutable (cannot be changed). They're faster, hashable, and perfect for data that shouldn't be modified.
15 min•By Priygop Team•Updated 2026
Tuples
Tuples
# Creating tuples
point = (3, 4)
rgb = (255, 128, 0)
single = (42,) # comma needed for single element!
empty = ()
from_list = tuple([1, 2, 3])
# Accessing (same as lists)
print(point[0]) # 3
print(rgb[-1]) # 0
print(point[0:2]) # (3, 4)
# Immutable — CANNOT modify!
# point[0] = 10 # TypeError!
# Tuple unpacking
x, y = point
print(f"x={x}, y={y}")
# Swap variables
a, b = 10, 20
a, b = b, a
print(f"a={a}, b={b}") # a=20, b=10
# Extended unpacking
first, *rest = [1, 2, 3, 4, 5]
print(first) # 1
print(rest) # [2, 3, 4, 5]
# Named tuples (cleaner than regular tuples)
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(f"x={p.x}, y={p.y}")
# When to use tuples vs lists:
# Tuples: fixed data, dict keys, function returns
# Lists: mutable collections, growing/shrinking dataTip
Tip
Use namedtuple for readable tuples: Point = namedtuple('Point', ['x','y']). Access with p.x instead of p[0].
Diagram
Loading diagram…
List for mutable sequences, tuple for immutable data, set for unique items
Common Mistake
Warning
Single-element tuple needs a comma: (42,) not (42). Without the comma, (42) is just an integer in parentheses.
Practice Task
Note
(1) Create a tuple and try to modify it. (2) Unpack a tuple into variables. (3) Swap two variables using tuple unpacking. (4) Use namedtuple.