Tuples - Immutable Sequences
Creating Tuples
t = (1, 2, 3)
t = 1, 2, 3 # Tuple packing
single = (42,) # Single element NEEDS comma!
empty = ()
Immutability
Tuples cannot be modified after creation:
t = (1, 2, 3)
# t[0] = 10 # TypeError!
Tuple Unpacking
x, y, z = (1, 2, 3)
a, b = b, a # Swap
first, *rest = (1, 2, 3, 4) # first=1, rest=[2,3,4]
Methods
Only two: count() and index()
Tuples vs Lists
| Feature | Tuple | List |
|---|---|---|
| Mutable | No | Yes |
| Hashable | Yes | No |
| Dict key | Yes | No |
| Performance | Faster | Slower |
Key Points
- Single element tuple:
(42,)with comma! - Tuples can be dictionary keys (hashable)
- Use for data that shouldn’t change