Unpacking
Reading a tuple by index works, but point[0] doesn't say what's in it. Instead, you can give each element a variable of its own, all in one line:
point = (3, 8)
x, y = point
print(x)
print(y)3
8On the left of the = are two names, separated by a comma. Python puts the first element of the tuple into the first name and the second element into the second. This is called unpacking.
You have used it before. In the lesson on dictionaries, for country, capital in capitals.items(): unpacked each pair of the dictionary into two loop variables. And without .items(), the loop got only the keys: Python tried to unpack a word such as "Czechia" into the two variables, and the program ended with ValueError: too many values to unpack (expected 2).
The number of names has to match the number of elements. When it doesn't, you get a ValueError that says how many values Python expected and how many it got:
x, y = (3, 8, 1)Traceback (most recent call last):
File "<exec>", line 1, in <module>
ValueError: too many values to unpack (expected 2, got 3)With too few elements, x, y, z = (3, 8) ends with ValueError: not enough values to unpack (expected 3, got 2).
Unpacking works with lists too, such as the list that .split() gives. A result saved as "Anna:12" splits into a name and a score:
name, score = "Anna:12".split(":")
print(name)
print(int(score) + 1)Anna
13The score is still text, "12", so you need int() to calculate with it. Without it, score >= 10 would end with TypeError: '>=' not supported between instances of 'str' and 'int': text and a number can't be compared.
One more trick: unpacking can swap the values of two variables in a single line.
first = "Tom"
second = "Anna"
first, second = second, first
print(first, second)Anna TomOn the right, second, first makes a tuple of the two values (it's the commas that make a tuple, even without parentheses), and Python then unpacks it into first and second.
Instructions
- 1
Split
resultat the colon and unpack the two parts into the variablesnameandscore, all in one line. Then print them:print(name, score)showsAnna 12. - 2
Players with at least 10 points go on to the final. Below, print
Anna goes to the final.if the score is 10 or more, andAnna is out.if it isn't, with the name taken fromname. Keep the lineresult = "Anna:12": the exercise also tries other results.