A List of Tuples
Tuples are often kept in a list, such as a list of results, each the name of a player and their score:
results = [("Anna", 12), ("Tom", 7), ("Eva", 15)]
print(results[2])
print(results[2][0])('Eva', 15)
EvaIt works like a list of lists: results[2] is the third tuple, and results[2][0] its first element, the name. The list can grow and shrink with .append() and .pop(), while each result in it stays as it was saved.
A for loop gets one tuple in each iteration. With two loop variables, it unpacks the tuple right away, just as it does with .items() of a dictionary. In fact, .items() gives tuples too: each pair of a dictionary is a tuple of the key and the value.
results = [("Anna", 12), ("Tom", 7), ("Eva", 15)]
for name, score in results:
print(f"{name} scored {score} points.")Anna scored 12 points.
Tom scored 7 points.
Eva scored 15 points.A list of tuples or a list of dictionaries? Both hold many things of the same kind. A tuple is shorter and fits two or three values whose order is clear, like a name and a score. A dictionary is better when there are more values, or when the code should say what each value means: movie["year"] says more than movie[1].
A typical mistake is adding a tuple without its own parentheses:
results = [("Anna", 12), ("Tom", 7)]
results.append("Lily", 11)Traceback (most recent call last):
File "<exec>", line 2, in <module>
TypeError: list.append() takes exactly one argument (2 given).append() adds one element, but it got two: "Lily" and 11. The tuple needs its own parentheses inside those of the call: results.append(("Lily", 11)).
Instructions
- 1
Lily has played too. Add her result, the tuple
("Lily", 11), to the end ofresultswith.append(). - 2
Below, write a
forloop with two loop variables that prints each result asAnna: 12. The output should be five lines, fromAnna: 12toLily: 11. Keep the lines of the list as they are: the exercise also tries other points. - 3
Finally, find the best player: below the loop, print
Best: Eva (15). Use the pattern for the largest value from the lesson on loops, starting with the first result. Tip:best_name, best_points = results[0]unpacks the first result into two variables.