Tuple Basics
Tuples are ordered, immutable sequences. Once created, their elements cannot be changed, added, or removed.
Creating Tuples
t1 = (1, 2, 3)
t2 = "a", "b", "c" # parentheses optional
t3 = (42,) # single-element (trailing comma!)
t4 = tuple([1, 2, 3]) # from list
empty = ()Accessing Elements
coords = (10.5, 20.3, 5.0)
print(coords[0]) # 10.5
print(coords[-1]) # 5.0
print(coords[1:]) # (20.3, 5.0)Unpacking
x, y, z = coords
print(x, y, z)
# Extended unpacking
first, *rest = (1, 2, 3, 4, 5)
print(first) # 1
print(rest) # [2, 3, 4, 5]Immutability
t = (1, 2, 3)
# t[0] = 99 # TypeError: 'tuple' does not support item assignment
# But if a tuple contains a list, the list IS mutable:
t2 = ([1, 2], [3, 4])
t2[0].append(3) # works!