Lesson 3 of 16 · Pythonic Code
Unpacking and Star Syntax
Learn Python unpacking: assign several variables at once, swap values, use enumerate and zip neatly, collect extra items with * and merge lists and dictionaries.
- 8 min read
- Intermediate
- Reviewed
- How to assign several variables from one list or tuple
- How to swap two variables in one line
- How to collect the remaining items with a star
- How to merge lists and dictionaries with * and **
Several variables at once
You already know that a function can return several values as a tuple. Unpacking puts the items of a tuple or list straight into separate variables.
point = (3, 7) x, y = point print(x) print(y)
The number of variables on the left must match the number of items on the right. Unpacking works with any sequence: tuples, lists, even strings.
name, age, city = ["Ada", 36, "London"] first, second, third = "abc" print(name, age, city) print(first, third)
Swapping two values
In many languages you need a temporary variable to swap two values. In Python you unpack.
a = 1 b = 2 a, b = b, a print(a, b)
The right side is built first as a tuple (2, 1), and then unpacked into a and b.
Unpacking in loops
You have used this without noticing. for name, price in prices.items() unpacks each key-value pair. The same works with enumerate() and zip().
fruits = ["apple", "banana", "cherry"]
prices = [30, 10, 120]
for position, fruit in enumerate(fruits, start=1):
print(position, fruit)
for fruit, price in zip(fruits, prices):
print(f"{fruit}: {price}")Collecting the rest with a star
Put * in front of one variable to collect "everything else" into a list.
scores = [92, 85, 78, 61, 45] best, *others = scores print(best) print(others) first, *middle, last = scores print(first, last) print(middle)
Only one variable may have a star. It always receives a list, which may be empty.
Ignoring values with an underscore
By convention, _ is the name for a value you do not need.
record = ("Ada", "[email protected]", "London", 36)
name, _, city, _ = record
print(name, city)Spreading a list into another
A star also works the other way round: inside a list, *items spreads the items out.
basics = ["Python", "SQL"] ml = ["NumPy", "scikit-learn"] roadmap = [*basics, "Statistics", *ml] print(roadmap)
Spreading into a function call
* spreads a list into separate arguments.
def describe(name, age, city):
print(f"{name} is {age} and lives in {city}")
person = ["Ada", 36, "London"]
describe(*person)describe(*person) is the same as describe("Ada", 36, "London").
Merging dictionaries with two stars
** spreads a dictionary. It is the neatest way to combine two dictionaries into a new one.
defaults = {"model": "small", "temperature": 0.7, "max_tokens": 200}
custom = {"temperature": 0.2}
settings = {**defaults, **custom}
print(settings)When both dictionaries contain the same key, the one written later wins. Here temperature comes from custom. Python also has a shorter way to write this: defaults | custom.
Common mistakes
Use unpacking with a star to split the race results.
race = ["Lena", "Omar", "Priya", "Kenji", "Sara"] # The list is in finishing order. # Unpack it into winner, runner_up and the_rest (a list of everyone else), # then print the three lines below. Output must be exactly: # Winner: Lena # Runner-up: Omar # Also finished: 3
After first, *rest = [10, 20, 30], what is rest?
Summary
a, b = pairunpacks a sequence into separate variables.a, b = b, aswaps two values.first, *rest = itemscollects the remaining items in a list.[*a, *b]merges lists,{**a, **b}merges dictionaries, andf(*args)spreads a list into arguments.
Next: slicing, the quickest way to take part of a list or string.
Finished reading? Tick it off to track your progress.