Python Arena
Step 2 of 3

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)
Output
(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)
Output
{(2, 3): 'gold', (0, 1): 'map'}
gold
False

With 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)
Output
{(0, 0): 3, (0, 1): 1, (1, 1): 1}

Your task

Challenge 1 of 3

The treasures of a map are in a dictionary whose keys are (row, column) tuples. Complete the program: it asks for a row and a column, as whole numbers, and prints what's in that square, or Nothing here if the square isn't a key. Use the prompts Row: and Column: . An example run:

Row: 2
Column: 3
gold

Challenge 2

What does this program print? Type each line it prints.

Challenge 3

Write a function count_visits(squares) that takes a list of (row, column) tuples and returns a dictionary in which each different square is a key and the value is how many times it's in the list.

For example, count_visits([(0, 0), (1, 2), (0, 0)]) returns {(0, 0): 2, (1, 2): 1}.