Beginner Fundamentals
Tuples
A tuple is like a list, but immutable: once created it can’t change. It uses parentheses.
point = (10, 20)
colors = ("red", "green", "blue")
Access
print(point[0]) # 10
print(colors[-1]) # blue
You can’t change it
point[0] = 5 # TypeError
To “change” it, convert to a list, edit, and convert back:
tmp = list(point)
tmp[0] = 5
point = tuple(tmp)
Unpack
x, y = point
print(x) # 5
print(y) # 20
Why use a tuple
- Data that shouldn’t change (coordinates, settings).
- Lighter and faster than a list.
- Can be a dictionary key (a list can’t).
Single-item tuple
You need the comma:
t = (5,) # tuple
x = (5) # just the number 5