Intermediate Python · Lesson 5 of 14
Unpacking and the star operator
Split tuples and lists into names in one line, catch the rest with a star, and use * and ** to spread lists and dictionaries into calls.
Unpacking means taking a tuple, list or any other sequence apart and giving each piece its own name in one assignment. You have already used it with low, high = .... The number of names must match the number of items.
point = (3, 7)
x, y = point
print(x, y)
name, city, year = ["Leila", "Cairo", 1998]
print(f"{name} from {city}, born {year}")
a, b = 1, 2
a, b = b, a
print(a, b)3 7 Leila from Cairo, born 1998 2 1
The last example swaps two variables without a temporary one.
Catching the rest with a star
Put a star in front of one name and it collects all the leftover items as a list. That makes the code work for sequences of any length. An underscore _ is the usual name for parts you do not need.
first, *rest = [10, 20, 30, 40]
print(first, rest)
*earlier, last = ["Mon", "Tue", "Wed"]
print(earlier, last)
head, *middle, tail = "Python"
print(head, middle, tail)
line = "2026-03-15,Coffee,3.20"
date, _, amount = line.split(",")
print(date, amount)10 [20, 30, 40] ['Mon', 'Tue'] Wed P ['y', 't', 'h', 'o'] n 2026-03-15 3.20
When the counts do not match, Python raises a ValueError.
try:
a, b = [1, 2, 3]
except ValueError:
print("Error: 3 values but only 2 names")Error: 3 values but only 2 names
Unpacking in loops
A for loop can unpack each item straight away, which is exactly what happens with enumerate(), zip() and dict.items(). Brackets let you unpack nested data too.
trips = [("Ana", ("Madrid", "Spain")), ("Yuki", ("Kyoto", "Japan"))]
for name, (city, country) in trips:
print(f"{name} visited {city}, {country}")
for i, (name, _) in enumerate(trips, start=1):
print(i, name)Ana visited Madrid, Spain Yuki visited Kyoto, Japan 1 Ana 2 Yuki
Spreading with * and **
Stars also work the other way round. In a call, *items spreads a list into separate positional arguments and **options spreads a dictionary into keyword arguments. Inside list and dictionary brackets they merge collections.
def describe(name, age, city):
return f"{name}, {age}, {city}"
data = ["Omar", 31, "Dubai"]
print(describe(*data))
info = {"city": "Oslo", "age": 25, "name": "Ingrid"}
print(describe(**info))
print(*["a", "b", "c"], sep=" | ")
fruit = ["apple", "pear"]
veg = ["leek"]
print([*fruit, *veg, "rice"])
defaults = {"size": "M", "colour": "black"}
choice = {"colour": "green"}
print({**defaults, **choice})Omar, 31, Dubai
Ingrid, 25, Oslo
a | b | c
['apple', 'pear', 'leek', 'rice']
{'size': 'M', 'colour': 'green'}When two dictionaries share a key, the one written later wins.
✎ Exercise
Each line holds a name followed by any number of scores. Use star unpacking to split the name from the scores, then print the name and the average score with one decimal place.
Hint: name, *scores = line.split(",") gives you the scores as a list of strings; convert them with int().
lines = ["Nadia,8,9,10", "Pablo,6,7", "Wei,9,9,8,10"]
for line in lines:
# your code here
pass
Expected output:
Nadia: 9.0 Pablo: 6.5 Wei: 9.0
Show a solution
lines = ["Nadia,8,9,10", "Pablo,6,7", "Wei,9,9,8,10"]
for line in lines:
name, *scores = line.split(",")
numbers = [int(s) for s in scores]
print(f"{name}: {sum(numbers) / len(numbers):.1f}")Nadia: 9.0 Pablo: 6.5 Wei: 9.0
Check yourself
1. After first, *rest = (1, 2, 3), what is rest?
A starred name always collects the leftovers as a list, even when the source is a tuple.
2. What does print(*[1, 2, 3]) show?
The star spreads the list into three separate arguments, and print puts spaces between them.
3. What is {**{"a": 1, "b": 2}, **{"b": 9}}?
Later values win when keys repeat, so b becomes 9.