Syntax
a, b, *rest = iterableExamples
Basic Unpacking
Assigning each item of an iterable to its own variable.
coordinates = (10, 20, 30)
x, y, z = coordinates
print(x, y, z) # 10 20 30
first, second = ["John", "Zain"]
print(first, second)Star Unpacking
Using * to capture multiple leftover items into a list.
numbers = [1, 2, 3, 4, 5]
first, *middle, last = numbers
print(first) # 1
print(middle) # [2, 3, 4]
print(last) # 5
head, *tail = numbers
print(head, tail) # 1 [2, 3, 4, 5]Unpacking in Function Calls
Using * and ** to spread a list or dictionary into a function's arguments.
def add(a, b, c):
return a + b + c
numbers = [1, 2, 3]
print(add(*numbers)) # 6, same as add(1, 2, 3)
def greet(name, greeting):
print(f"{greeting}, {name}!")
info = {"name": "John", "greeting": "Hi"}
greet(**info) # unpacks dict into keyword argumentsUnpacking Nested Structures
Unpacking works with nested tuples and lists too.
point = (("x", 3), ("y", 4))
(x_label, x_val), (y_label, y_val) = point
print(f"{x_label}={x_val}, {y_label}={y_val}") # x=3, y=4
# Common pattern: unpacking while iterating
pairs = [(1, "one"), (2, "two"), (3, "three")]
for number, word in pairs:
print(f"{number}: {word}")Best practices
- Use unpacking instead of manual indexing when you know exactly how many items an iterable contains
- Use *rest to flexibly capture 'everything else' without knowing the exact length in advance
- Use *args-style unpacking (*numbers) to spread a list into a function call rather than passing the list itself when separate arguments are expected
- Unpacking raises a ValueError if the number of variables does not match the number of items - use * to handle variable-length iterables safely
Runtime & versions
Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Python language reference