A tuple is an ordered, unchangeable collection: point = (10, 20).
Create
colors = ("red", "green")- Brackets are optional:
t = 1, 2, 3 - One item needs a comma:
(5,)—(5)is just the number 5 tuple([1, 2])converts a list
Access
Like lists: t[0], t[-1], slicing, len(), in, count(), index().
Immutable
You cannot change, add or remove items. To "change" one, build a new tuple.
Unpacking
x, y = pointname, *rest = ("Asha", 21, "Patna")—restgets the remaining items as a list- Functions return several values as a tuple:
return total, average
Why use tuples?
- Data that should not change (coordinates, RGB colours, database rows)
- Slightly faster and smaller than lists
- Can be dictionary keys (lists cannot)
namedtuple (from collections) gives tuple fields names: p.x, p.y.
Example
Example — Tuples and unpacking
Python
from collections import namedtuple
def stats(numbers):
return min(numbers), max(numbers), sum(numbers) / len(numbers)
low, high, avg = stats([72, 88, 95, 64])
print(f"Low {low}, High {high}, Avg {avg:.1f}")
student = ("Asha", 21, "Patna", "BCA")
name, age, *others = student
print(name, age, others)
single = (5,)
print(type(single), type((5)))
distances = {("Patna", "Delhi"): 1000}
print(distances[("Patna", "Delhi")])
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p.y, p)
Output: Low 64, High 95, Avg 79.8; Asha 21 ['Patna', 'BCA']; <class 'tuple'> <class 'int'>; 1000; 3 4 Point(x=3, y=4)