Legends ofPythos
Claim your name
Pythonic Python

Unpacking like a Python programmer

Lesson 2 of 12

Watch the lesson5:38 · with Sigrid
Mental model: Think of unpacking as opening a gift box where each item is already labelled for you. Instead of digging through layers, Python hands you each part directly into the variables you named.

Unpacking pairs

orders = [(101, 'Laptop'), (204, 'Mouse')]
for order_id, product in orders:
    print(f"Order {order_id}: got a {product}")

# Order 101: got a Laptop
# Order 204: got a Mouse
Each tuple splits into two variables automatically.
Python matches the shape of each item to your variable names. That's clearer than writing for order in orders: and picking each part out by its position, with order[0] and order[1]. It reads like a sentence.

Starred unpacking

temperatures = [22, 20, 24]
first_day, *later_days = temperatures
print(f"First: {first_day}°")
print(f"Rest: {later_days}")

# First: 22°
# Rest: [20, 24]
* collects the remaining items into a list.
You can place *rest in other positions too. For example, first, *middle, last = [10, 20, 30] gives you the first and last elements separately, with everything else collected into a list.

Unpacking dictionaries

def format_user(name, age, city):
    return f"{name} is {age} from {city}"

profile = {'name': 'Ada', 'age': 36,
           'city': 'London'}
print(format_user(**profile))
# Ada is 36 from London
** spreads a dictionary out: each key becomes a keyword argument.
The ** operator takes each key-value pair and passes it as a named argument. So format_user(**profile) works like format_user(name='Ada', age=36, city='London'). The keys must match the parameter names, or Python stops with a TypeError.

Ignoring values

user = ('Ada', 36, 'London')
name, _, city = user
print(name, city)

# Ada London
_ says out loud that the age is not needed here.
When you don't need a value, name it _. _ is a real name, and here it does hold 36. But it tells anyone reading your code that this value isn't needed, so they can see at a glance which parts of the data matter.

Your turn

0 of 3 solved

Exercise 1

+30 XP
Write a function sum_pairs(pairs) that takes a list of two-element tuples and returns the sum of all first elements plus twice each second element.

For example, if pairs = [(1, 2), (3, 4)], return 1 + 2*2 + 3 + 2*4 = 16.
Write your Python here.

Run your code to check it against the tests.

Exercise 2

+30 XP
Write a function split_list(nums) that takes a non-empty list and returns a tuple (first, rest) where first is the first element and rest is a list of all remaining elements.

Use starred unpacking to do this in one assignment.
Write your Python here.

Run your code to check it against the tests.

Exercise 3

+30 XP
Write a function format_user(user) that takes a dictionary with the keys 'name', 'age' and 'city', and returns the text "Name (Age) - City".

Use ** unpacking to pass the dictionary into a helper function called build(name, age, city), which you must also define.

Careful: the page's format_user takes three values. Yours takes one dictionary, user, and hands it on to build.
Write your Python here.

Run your code to check it against the tests.