Introduction
Tuples are ordered, immutable collections. They're similar to lists but cannot be modified after creation.
Creating Tuples
# Basic tuple
point = (3, 4)
colors = ("red", "green", "blue")
# Single element (needs comma)
single = (42,)
# Tuple unpacking
x, y = point
a, b, c = colors
Tuple Operations
coords = (10, 20, 30)
# Accessing
print(coords[0]) # 10
print(coords[1:3]) # (20, 30)
# Count and index
print(coords.count(10))
print(coords.index(20))
# Membership
print(20 in coords) # True
Named Tuples
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p.x, p.y)
Practice Problems
- Swap values using tuple unpacking
- Return multiple values from function
- Use tuple as dictionary keys
- Convert between list and tuple
- Implement immutable data structure with named tuples