What a tuple is
A tuple is a lot like a list: an ordered group of values that you can index, slice, loop over and measure with len. There are two differences. You write a tuple with parentheses ( ) instead of square brackets, and a tuple can't change after it's made.
point = (3, 7)
print(point)
print("x:", point[0])
print("y:", point[1])
colors = ("red", "green", "blue")
print(len(colors), colors[-1])
print("green" in colors)
for color in colors[1:]:
print(color)
(3, 7)
x: 3
y: 7
3 blue
True
green
bluePython shows a tuple in parentheses, and a slice of a tuple is a tuple too.
A tuple can't change
Tuples are immutable, like strings and numbers. Assigning to an index stops the program:
point = (3, 7)
point[0] = 4
Traceback (most recent call last):
File "main.py", line 2, in <module>
point[0] = 4
~~~~~^^^
TypeError: 'tuple' object does not support item assignmentA tuple has none of the methods that change a list either: no append, remove or sort.
>>> colors = ("red", "green")
>>> colors.append("blue")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'Functions that only read work fine: len, min, max, sum and sorted (which returns a new list). When a tuple needs to be different, make a new tuple and give it to the variable:
>>> point = (3, 7)
>>> point = (4, point[1])
>>> point
(4, 7)Lists of tuples
A tuple suits a small record whose parts belong together, such as a name and a year. A list can hold many such tuples:
pioneers = [("Ada", 1815), ("Alan", 1912), ("Grace", 1906)]
for pioneer in pioneers:
print(f"{pioneer[0]} was born in {pioneer[1]}")
Ada was born in 1815
Alan was born in 1912
Grace was born in 1906The list can grow and shrink as people are added or removed, but each record stays the way it was made.