Tuples — Creating Tuples and Operations
A tuple is an ordered, immutable collection, written with parentheses ().
Creating Tuples
empty = ()
single = (5,) # comma is REQUIRED for a single-element tuple
t = (1, 2, 3)
without_parens = 1, 2, 3 # parentheses are optional
mixed = (1, "two", 3.0)
from_list = tuple([1, 2, 3])
nested = ((1, 2), (3, 4))
x = (5) # this is just an int, NOT a tuple!
y = (5,) # this IS a tuple
print(type(x), type(y)) # <class 'int'> <class 'tuple'>
Tuples are Immutable
t = (1, 2, 3)
# t[0] = 100 # TypeError: 'tuple' object does not support item assignment
Tuple Operations
| Operation | Example | Result |
|---|---|---|
len() | len((1,2,3)) | 3 |
Concatenation + | (1,2) + (3,4) | (1,2,3,4) |
Repetition * | (1,2) * 2 | (1,2,1,2) |
Membership in | 2 in (1,2,3) | True |
max() | max((3,1,5)) | 5 |
min() | min((3,1,5)) | 1 |
t1 = (1, 2, 3)
t2 = (4, 5)
print(len(t1)) # 3
print(t1 + t2) # (1, 2, 3, 4, 5)
print(t1 * 2) # (1, 2, 3, 1, 2, 3)
print(2 in t1) # True
print(max(t1), min(t1)) # 3 1
Accessing and Slicing (same as lists)
t = (10, 20, 30, 40, 50)
print(t[0]) # 10
print(t[-1]) # 50
print(t[1:4]) # (20, 30, 40)
Tuple Unpacking
point = (10, 20)
x, y = point
print(x, y) # 10 20
a, *rest = (1, 2, 3, 4)
print(a, rest) # 1 [2, 3, 4]
Why use tuples over lists?
- Immutability protects data from accidental modification.
- Tuples are slightly faster and use less memory than lists.
- Tuples can be used as dictionary keys; lists cannot (lists are unhashable).