Tuples and unpacking
A tuple is an ordered sequence that cannot change after it is made. Use one for a fixed group of values, such as a point or a record, and a list for a collection that grows.
point = (3, 4)
x, y = point # unpacking
first, *rest = [1, 2, 3, 4]
print(x, y, first, rest) # 3 4 1 [2, 3, 4]
single = (5,) # the comma makes it
print(type(single).__name__) # tuple
print((1, 2) == [1, 2]) # False- Unpacking needs as many names as there are items, unless one name has a star, which collects the rest into a list.
- A function returns several values by returning a tuple, and the caller unpacks it.
- A tuple and a list with the same items are not equal.
- Tuples can be dict keys and set members, because they cannot change. Lists cannot.
grid = {(0, 0): "start", (2, 1): "goal"}
for (row, col), name in grid.items():
print(row, col, name)Your task
Write min_max(numbers) returning a (smallest, largest) tuple for a non-empty list. Write walk(steps) that starts at (0, 0), adds each (dx, dy) step in turn, and returns the final position as a tuple.
The explanation opens here once every check passes.