typestar

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

  1. A tuple unpacks straight into two variables.
  2. A starred name like *middle soaks up the rest.
  3. Loops unpack each pair as it arrives.

Keywords and builtins used here

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.

Type this snippet

Step 6 of 6 in Variables & types, step 6 of 72 in Language basics.

← Previous Next →