Unpacking sequences in Python
Pulling a sequence apart into named pieces in one statement.
point = (3, 7)
x, y = point
first, *middle, last = [1, 2, 3, 4, 5]
low, high = 10, 99
low, high = high, low
pairs = [("a", 1), ("b", 2)]
for letter, value in pairs:
print(letter, value)
head, tail = pairs[0], pairs[1:]
How it works
- A tuple unpacks straight into two variables.
- A starred name like
*middlesoaks up the rest. - Loops unpack each pair as it arrives.
Keywords and builtins used here
forprint
The run, in numbers
- Lines
- 13
- Characters to type
- 222
- Tokens
- 90
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 64 seconds.
Step 6 of 6 in Variables & types, step 6 of 72 in Language basics.