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 MousePython 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.