Unpacking takes the items out of a list, tuple or other iterable and puts each one in its own variable, all in one line. With the star signs * and ** you can also collect “the rest” of the items, pass a list as separate arguments, and join lists and dictionaries together. These small tools make Python code shorter and much easier to read.
In this lesson you will learn
- Unpacking into several variables, and swapping values
- Collecting extra items with
*rest - Nested unpacking and unpacking in
forloops - Spreading arguments with
*and**in function calls - Merging lists and dictionaries, and
zip(*rows)
You should know tuples, dictionaries and *args and **kwargs.
Unpacking Into Variables
# Basic unpacking: one name per item
point = (23.8, 90.4)
lat, lon = point
print("lat", lat, "lon", lon)
# Swap without a temporary variable
a, b = 5, 9
a, b = b, a
print("a =", a, "b =", b)
# Star collects "the rest" into a list
first, *middle, last = [10, 20, 30, 40, 50]
print(first, middle, last)
head, *tail = "Dhaka"
print(head, tail)
# Nested unpacking
student = ("Nusrat", (3.82, "CSE"))
name, (cgpa, dept) = student
print(name, cgpa, dept)
# Unpacking in a for loop
scores = [("Arif", 72), ("Tania", 95), ("Mitu", 88)]
for who, mark in scores:
print(f"{who:6} {mark}")
# _ for values you do not need
_, month, _ = "2026-11-19".split("-")
print("month:", month)
# Too many or too few values is an error
try:
x, y = [1, 2, 3]
except ValueError as e:
print("ValueError:", e)
Output
lat 23.8 lon 90.4
a = 9 b = 5
10 [20, 30, 40] 50
D ['h', 'a', 'k', 'a']
Nusrat 3.82 CSE
Arif 72
Tania 95
Mitu 88
month: 11
ValueError: too many values to unpack (expected 2)
lat, lon = pointputs the first item inlatand the second inlon. The number of names must match the number of items.a, b = b, aswaps two values. Python builds the tuple on the right first, then unpacks it, so no temporary variable is needed.- A name with a star, such as
*middle, collects all the items that the other names did not take. It always becomes a list, even when it is empty. Only one starred name is allowed. - Strings are iterable too, so
head, *tail = "Dhaka"splits off the first letter. - Brackets on the left match the shape of nested data:
name, (cgpa, dept) = student. - A
forloop can unpack each item as it goes, which is the usual way to loop over pairs. - By habit,
_is a name for values you do not need. - If the counts do not match, Python raises
ValueError.
Spreading With * and **
# * in a function call spreads a list into separate arguments
def area(width, height):
return width * height
size = [4, 6]
print("area:", area(*size))
# ** spreads a dictionary into keyword arguments
def describe(name, city, age):
return f"{name}, {age}, from {city}"
info = {"name": "Rafi", "city": "Khulna", "age": 21}
print(describe(**info))
# Building new lists and dicts with * and **
odd = [1, 3, 5]
even = [2, 4, 6]
print([*odd, *even, 7])
print({*odd, *odd}) # a set removes duplicates
defaults = {"theme": "light", "lang": "en", "font": 14}
user = {"lang": "bn", "font": 16}
settings = {**defaults, **user} # later values win
print(settings)
print(defaults | user) # the same with | (Python 3.9+)
# print(*items) prints each item as a separate argument
items = ["mango", "jackfruit", "lychee"]
print(*items, sep=" | ")
# zip(*rows) turns rows into columns
rows = [("Arif", 72), ("Tania", 95), ("Mitu", 88)]
names, marks = zip(*rows)
print(names)
print(marks)
Output
area: 24
Rafi, 21, from Khulna
[1, 3, 5, 2, 4, 6, 7]
{1, 3, 5}
{'theme': 'light', 'lang': 'bn', 'font': 16}
{'theme': 'light', 'lang': 'bn', 'font': 16}
mango | jackfruit | lychee
('Arif', 'Tania', 'Mitu')
(72, 95, 88)
- In a function call,
*sizespreads the list into separate arguments:area(*[4, 6])is the same asarea(4, 6). **infospreads a dictionary into keyword arguments. The keys must match the parameter names.- Inside brackets,
[*odd, *even, 7]builds one new list from several.{*a, *b}builds a set. {**defaults, **user}merges two dictionaries into a new one. When a key appears in both, the later one wins, so the user’s “bn” replaces “en”. Since Python 3.9,defaults | userdoes the same.print(*items, sep=" | ")prints each item as its own argument.zip(*rows)passes each row tozipas a separate argument.zipthen groups the first items together and the second items together, which turns rows into columns.
The star means two things
In a function definition, def f(*args) collects arguments into a tuple. In a function call, f(*items) spreads a list into arguments. They are opposite jobs that use the same symbol.
Common Mistakes
- Two starred names, as in
*a, *b = items. Python cannot tell where one ends, so this is a syntax error. - Expecting a tuple from
*rest. It is always a list. - Unpacking a dictionary directly.
a, b = {"x": 1, "y": 2}gives the keys. Use.items()or.values()for the rest. - Merging dictionaries in the wrong order. In
{**user, **defaults}, the defaults would overwrite the user’s choices.
Practice Exercises
Exercise 1. From marks = [45, 88, 72, 91, 60], use one unpacking line to get the first mark, the last mark and a list of the others.
Show answer
marks = [45, 88, 72, 91, 60]
first, *others, last = marks
print(first, others, last) # 45 [88, 72, 91] 60
Exercise 2. Write a function full_name(first, last). Call it with the dictionary {"last": "Rahman", "first": "Tania"} without writing the two values out again.
Show answer
def full_name(first, last):
return f"{first} {last}"
person = {"last": "Rahman", "first": "Tania"}
print(full_name(**person)) # Tania Rahman
** matches by name, so the order of the keys does not matter.
Frequently Asked Questions
Does unpacking work with any iterable?
Yes. Lists, tuples, strings, sets, ranges, generators and files can all be unpacked. With a set the order is not guaranteed, so unpacking a set into named variables is rarely a good idea.
Is a, b = b, a really safe for swapping?
Yes. Python works out every value on the right side before it assigns anything, so neither value is lost. It works for any number of names, such as a, b, c = c, a, b.
Summary
a, b = pairunpacks items into names; the counts must match.first, *rest = itemscollects extra items into a list.- In a call,
*spreads a list and**spreads a dictionary. [*a, *b]and{**d1, **d2}build merged lists and dictionaries.
