Summary
In this lesson, you learned that:
- A tuple keeps together a few values that make up one thing:
treasure = (4, 7). You read its elements by index, andlen(),inandforwork on it, but it can't be changed:treasure[0] = 5ends with aTypeError. When the thing changes, store a new tuple in the variable. - Unpacking puts the elements into variables in one line:
x, y = treasure. The number of names must match the number of elements, otherwise the program ends with aValueError. It works with lists too:name, score = "Anna:12".split(":"). a, b = b, aswaps two variables. The commas on the right make a tuple, even without parentheses.- A function returns several values separated by commas, as one tuple:
return lowest, highest. The call unpacks them:lowest, highest = lowest_and_highest(temperatures). - In a list of tuples,
for name, score in results:unpacks each tuple into two loop variables, as.items()does with the pairs of a dictionary. A new tuple goes into the list with its own parentheses:results.append(("Lily", 11)). enumerate()gives a loop each element with its number:for number, name in enumerate(players, start=1):. Withoutstart=1, it counts from 0.- A set holds each value only once and has no order:
{"dog", "cat"}. It has no indexes, and a printed set of texts can come out in a different order every run.set(votes)makes a set from a list without its duplicates,len()counts the different values andinchecks whether a value is there.set()is an empty set,{}an empty dictionary. .add()adds a value to a set (one that is already there isn't added twice),.discard()removes a value if it's there, and.remove()ends with aKeyErrorwhen it isn't.a & bholds what is in both sets,a | bwhat is in at least one of them, anda - bwhat is inabut not inb.
Now practice on the games in the editor: each tuple is a player and the score of one game. In the next lesson, Sorting, you'll learn to put values in order, for example results from the best to the worst, or the players of a set from A to Z.
Instructions
- 1
Print every game, numbered from 1 with
enumerate():1. Anna: 12,2. Tom: 7and so on, up to5. Tom: 11. Keep the lines of the list: the exercise also tries other games. - 2
Below, collect the names of the players in a set, and print how many different players there were:
Players: 3.