A tuple is an ordered, immutable collection enclosed in parentheses ():
point = (3, 4)
rgb = (255, 128, 0)
single = (1,) # trailing comma required
empty = ()
coordinates = 10, 20 # parentheses optional
Once created, a tuple cannot be changed:
t = (1, 2, 3)
# t[0] = 99 # TypeError!
# t.append(4) # AttributeError!
# t.pop() # AttributeError!
However, if a tuple contains mutable objects, those objects can be modified:
t = ([1, 2], [3, 4])
t[0].append(99) # t is now ([1, 2, 99], [3, 4])
t = ("a", "b", "c", "d", "e")
t[0] # "a"
t[-1] # "e"
t[1:3] # ("b", "c")
t[::-1] # ("e", "d", "c", "b", "a")
# Packing
person = "Alice", 30, "Engineer"
# Unpacking
name, age, job = person
print(name) # Alice
print(age) # 30
# Extended unpacking (Python 3+)
first, *middle, last = (1, 2, 3, 4, 5)
print(first) # 1
print(middle) # [2, 3, 4]
print(last) # 5
nested = ((1, 2), (3, 4), (5, 6))
print(nested[0][1]) # 2
# Flatten a nested tuple
flat = tuple(item for row in nested for item in row)
print(flat) # (1, 2, 3, 4, 5, 6)
The collections.namedtuple factory creates lightweight, immutable objects with named fields:
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(10, 20)
print(p.x) # 10
print(p.y) # 20
print(p[0]) # 10 (indexing still works)
Person = namedtuple("Person", "name age job")
alice = Person("Alice", 30, "Engineer")
print(alice.name) # Alice
Use ._replace() to create a new instance with modified fields:
alice2 = alice._replace(age=31)
print(alice2) # Person(name='Alice', age=31, job='Engineer')
t = (1, 2, 3, 2, 4, 2)
t.count(2) # 3
t.index(3) # 2
# t.index(10) # ValueError: tuple.index(x): x not in tuple
| Feature | Tuple | List |
|---|---|---|
| Mutable | No | Yes |
| Syntax | () | [] |
| Hashable | Yes (if contents are) | No |
| Use case | Fixed data, dict keys | Dynamic collections |
| Performance | Slightly faster | Slightly slower |
(1,) not (1). Without the comma, (1) is just the integer 1 in parentheses.
Create a namedtuple called Student with fields name, grade, and subjects (list of subject names). Create 3 students. Write a function that takes a tuple of students and returns the student with the highest grade. Print each student's details and the top student's info. Demonstrate packing, unpacking, and indexing.