📘 Lesson 12 · Intermediate

Python Tuples

Understand immutable tuples, unpacking, and when to use tuples vs lists.

Tuples vs Lists

Tuples use parentheses () and are immutable — once created, you cannot add, change, or remove items. This makes them perfect for data that should never change, like a coordinate pair or an RGB colour. They are also slightly faster than lists and can be used as dictionary keys (lists cannot, because they're mutable).

create.py
point = (3, 7)          # 2D coordinate
rgb = (255, 128, 0)      # orange colour
single = (42,)           # trailing comma makes it a tuple!

print(point)
print(rgb[0])            # access by index
print(type((42,)))       # tuple
print(type((42)))        # just int in brackets!
▶ Output
(3, 7)
255

The trailing comma in (42,) is essential — without it, Python treats the parentheses as grouping, not as a tuple. This is a common gotcha.

Tuple Unpacking

Unpacking assigns the values of a tuple to individual variables in one line. Python matches by position. This is very common in Python — functions that return multiple values use it, as does the elegant one-line variable swap shown below.

unpack.py
point = (10, 20)
x, y = point
print(f"x={x}, y={y}")

# Elegant swap — no temp variable needed
a, b = 1, 2
a, b = b, a
print(f"a={a}, b={b}")

# Extended unpacking — * collects remainder
first, *rest = (1, 2, 3, 4, 5)
print(first, rest)
▶ Output
x=10, y=20
a=2, b=1
1 [2, 3, 4, 5]

Tuple Methods

Because tuples are immutable, they have only two methods. count(x) counts how many times x appears. index(x) returns the position of the first occurrence. All other sequence operations — len, in, slicing, iteration — still work on tuples.

methods.py
t = (1, 2, 3, 2, 4, 2)
print(t.count(2))   # 2 appears 3 times
print(t.index(3))   # 3 is at position 2
print(4 in t)        # membership test
print(t[1:4])       # slicing works
▶ Output
3
2
True
(2, 3, 2)
Use tuples for fixed data (coordinates, database rows, config constants). Use lists when you need to add, remove, or reorder items.

🧠 Quick Check

How do you correctly create a single-element tuple?

(42)
[42]
(42,)
{42}

Tags

tuplesimmutableunpackingtuple methodspython collections