What tuples are for
A list can do almost everything a tuple can, and more. So why have tuples at all? Because a tuple says something about the data.
A list is a collection that may grow and shrink, usually of things of the same kind: the guests, the scores, the words. A tuple is a fixed group of values that belong together and only make sense together: the x and y of a point, the red, green and blue of a color, the year, month and day of a date. A point always has exactly two coordinates. Nobody should append a third one to it, and with a tuple, nobody can.
A function that works with such values gives back a new tuple instead of changing the old one:
def move(point: tuple, dx: int, dy: int) -> tuple:
return (point[0] + dx, point[1] + dy)
start = (2, 5)
end = move(start, 3, -1)
print(start, end)
(2, 5) (5, 4)move can't change start by accident, so there are no side effects to worry about: the original point is safe.
Tuples as dictionary keys
Because a tuple can't change, it can be a dictionary key, which a list can't. This makes a dictionary a handy map of a grid. The key is a pair of a row and a column, and only the squares that have something on them need to be stored:
treasures = {}
treasures[(2, 3)] = "gold"
treasures[(0, 1)] = "map"
print(treasures)
print(treasures[(2, 3)])
print((1, 1) in treasures)
{(2, 3): 'gold', (0, 1): 'map'}
gold
FalseWith a list as the key, as in treasures[[2, 3]] = "gold", Python would stop with the TypeError about an unhashable type from the dictionaries module.
Here the dictionary also counts how often each square of a grid was visited, with the counting pattern from the dictionaries module:
steps = [(0, 0), (0, 1), (0, 0), (1, 1), (0, 0)]
visits = {}
for square in steps:
if square not in visits:
visits[square] = 0
visits[square] += 1
print(visits)
{(0, 0): 3, (0, 1): 1, (1, 1): 1}