Back to series
· 10 min read

Python Sequence Unpacking and Extended Unpacking


I. What Is Sequence Unpacking

Sequence unpacking is an assignment syntax provided by Python that lets you assign the elements of an iterable, in order and by position, to multiple variables.

The traditional approach requires fetching each element one by one by index:

user = ("Alice", 25, "Beijing")

name = user[0]
age = user[1]
city = user[2]

print(name)
print(age)
print(city)

With sequence unpacking, this can be simplified to:

user = ("Alice", 25, "Beijing")

name, age, city = user

print(name)
print(age)
print(city)

Output:

Alice
25
Beijing

Python assigns the elements of the iterable on the right to the variables on the left, in order.

The basic syntax is:

variable1, variable2, ..., variableN = iterable

Key characteristics of sequence unpacking:

  • Assignment is positional, with each element mapped to its corresponding variable.
  • The number of variables on the left must usually match the number of elements on the right.
  • The right side can be a list, tuple, string, set, dictionary, or any other iterable.
  • Unpacking is essentially an assignment operation; the right side does not have to be a list or tuple.
  • Unpacking can be used for swapping variables, receiving function return values, and iterating in loops.

Note: although sequence unpacking is frequently used with lists and tuples, it is not a syntax aimed only at sequence types — it is built on Python's iterable protocol.

II. Basic Sequence Unpacking

1. Unpacking Lists

A list can be unpacked directly, assigning its elements to multiple variables.

numbers = [10, 20, 30]

a, b, c = numbers

print(a)  # 10
print(b)  # 20
print(c)  # 30

2. Unpacking Tuples

Tuples are one of the most common use cases for sequence unpacking.

person = ("Alice", 25, "Engineer")

name, age, job = person

print(name)
print(age)
print(job)

When unpacking a tuple, the outer parentheses can also be omitted:

person = "Alice", 25, "Engineer"

name, age, job = person

In fact, in Python it is the comma that creates a tuple; parentheses are usually just for grouping.

3. Unpacking Strings

Strings are also iterables, so they can be unpacked character by character.

text = "ABC"

a, b, c = text

print(a)  # A
print(b)  # B
print(c)  # C

If the number of characters in the string does not match the number of variables, an unpacking error occurs.

text = "Python"

a, b, c = text

Result of running:

ValueError: too many values to unpack (expected 3)

4. Unpacking Dictionaries

When a dictionary is iterated directly, it yields keys by default, not key-value pairs.

user = {
    "name": "Alice",
    "age": 25,
    "city": "Beijing"
}

a, b, c = user

print(a)  # name
print(b)  # age
print(c)  # city

If you need to get both keys and values at the same time, you can use items():

user = {
    "name": "Alice",
    "age": 25
}

for key, value in user.items():
    print(key, value)

Output:

name Alice
age 25

Here, each iteration unpacks one key-value pair tuple into the two variables key and value.

Note: unpacking a dictionary depends on the iteration order of its keys. Since Python 3.7, dictionary insertion order has been behavior guaranteed by the language specification.

III. Nested Sequence Unpacking

When the data on the right has a nested structure, you can use a matching nested structure on the left.

For example:

data = ("Alice", (25, "Beijing"))

name, (age, city) = data

print(name)
print(age)
print(city)

Output:

Alice
25
Beijing

Python unpacks layer by layer, following the structure.

Here is a more complex example:

students = [
    ("Alice", 90, ("Python", "Java")),
    ("Bob", 85, ("Go", "Rust"))
]

for name, score, (first, second) in students:
    print(name, score, first, second)

Output:

Alice 90 Python Java
Bob 85 Go Rust

Nested unpacking is particularly well suited to data structures with a fixed hierarchy, for example:

  • Database query results.
  • Coordinate and geometric data.
  • Multi-level configuration data.
  • Structured tuples returned by APIs.
  • Records with a fixed number of fields.

Note that nested unpacking requires the structure at each corresponding level to match. If the number of elements at any level differs, a ValueError will likewise be raised.

IV. Variable Swapping

Python can swap two variables using sequence unpacking, without defining an extra temporary variable.

Traditional approach:

a = 10
b = 20

temp = a
a = b
b = temp

print(a, b)

Using sequence unpacking:

a = 10
b = 20

a, b = b, a

print(a, b)

Output:

20 10

The execution process can be understood as:

Read the current values of the right-hand variables
        |
        v
Build the right-hand result to be assigned
        |
        v
Assign the results to the left-hand variables in order

Python first evaluates the right-hand expression, and then assigns to the left-hand targets.

Therefore:

a, b = b, a

The later read of b will not be affected by a having been modified first.

Variable swapping can also be extended to multiple variables:

a, b, c = 1, 2, 3

a, b, c = c, a, b

print(a, b, c)

Output:

3 1 2

V. The Problem of Mismatched Unpacking Counts

Ordinary sequence unpacking requires the number of elements on both sides to be the same.

For example:

a, b = [10, 20]

This executes normally.

But the following code raises an exception:

a, b = [10, 20, 30]

Exception:

ValueError: too many values to unpack (expected 2)

If there are not enough elements on the right side, an error is also raised:

a, b, c = [10, 20]

Exception:

ValueError: not enough values to unpack (expected 3, got 2)

The difference between the two errors:

Error Type Cause Example
too many values Too many elements on the right side Two variables receiving three elements
not enough values Not enough elements on the right side Three variables receiving two elements

If the data length is not fixed, ordinary unpacking is not flexible enough. In this case, extended unpacking can be used.

VI. Extended Unpacking: Star Expressions

Extended unpacking (Extended Iterable Unpacking) allows a starred target in an assignment, collecting multiple remaining elements into a list.

For example:

numbers = [10, 20, 30, 40, 50]

first, *middle, last = numbers

print(first)
print(middle)
print(last)

Output:

10
[20, 30, 40]
50

Here:

  • first receives the first element.
  • middle receives all the remaining elements in the middle.
  • last receives the last element.

The * in extended unpacking means to collect the remaining elements.

1. Basic Syntax

first, *rest = iterable

This form assigns the first element to first and collects the remaining elements into the rest list.

numbers = [1, 2, 3, 4]

first, *rest = numbers

print(first)  # 1
print(rest)   # [2, 3, 4]

You can also unpack from the end:

numbers = [1, 2, 3, 4]

*rest, last = numbers

print(rest)  # [1, 2, 3]
print(last)  # 4

You can also capture both the beginning and the end at the same time:

numbers = [1, 2, 3, 4, 5, 6]

first, *middle, last = numbers

print(first)   # 1
print(middle)  # [2, 3, 4, 5]
print(last)    # 6

2. The Starred Variable Always Receives a List

No matter what iterable the right-hand side originally is, the starred target in extended unpacking will always end up receiving a list.

numbers = (1, 2, 3, 4)

first, *rest = numbers

print(type(first))
print(type(rest))

Output:

<class 'int'>
<class 'list'>

Even if the right-hand side is a tuple, rest is still a list.

3. Remaining Elements Are Empty

If there are no remaining elements, the starred variable gets an empty list rather than raising an error.

numbers = [10]

first, *rest = numbers

print(first)  # 10
print(rest)   # []

Consider another case:

numbers = [10, 20]

first, last, *rest = numbers

print(rest)  # []

This allows extended unpacking to naturally handle data of different lengths.

4. Position of the Starred Target

The starred target can appear in different positions among the assignment targets on the left side, but only one starred target can appear at the same level.

Valid syntax:

first, *rest = [1, 2, 3]
*rest, last = [1, 2, 3]
first, *middle, last = [1, 2, 3, 4]

Invalid syntax:

*a, *b = [1, 2, 3, 4]

Having multiple starred targets at the same level triggers a SyntaxError.

7. Nested Use of Extended Unpacking

Extended unpacking can handle not only one-dimensional data but can also be combined with nested unpacking.

data = [
    ("Alice", 90, 85, 95),
    ("Bob", 80, 88, 92)
]

for name, *scores in data:
    print(name)
    print(scores)

Output:

Alice
[90, 85, 95]
Bob
[80, 88, 92]

You can also use a star in nested structures:

data = (
    "Alice",
    (90, 85, 95),
    "Beijing"
)

name, (*scores,), city = data

However, the inner syntax here requires the inner level to contain only one element—an iterable—so it is not suitable for expressing an ordinary split of a score list.

A more common and readable way is:

data = (
    "Alice",
    (90, 85, 95),
    "Beijing"
)

name, scores, city = data
first, *remaining = scores

print(name)
print(first)
print(remaining)
print(city)

In real-world projects, it is recommended to prefer unpacking patterns that are clear and easy to understand, rather than over-nesting just to reduce the number of lines of code.

8. Differences Between Extended Unpacking and Slicing

Both extended unpacking and slicing can extract some elements, but they work in different ways.

Slicing:

numbers = [10, 20, 30, 40, 50]

first = numbers[0]
middle = numbers[1:-1]
last = numbers[-1]

Extended unpacking:

numbers = [10, 20, 30, 40, 50]

first, *middle, last = numbers

Both approaches can produce similar results, but their use cases differ.

Comparison Aspect Extended Unpacking Slicing
Core use Assign variables by structure Extract some elements
Syntax first, *rest = data data[1:]
Variable binding Directly assigns to multiple variables Requires additional assignment
Length requirement Fixed targets must match Can handle out-of-range index bounds
Asterisk result Always a list Usually preserves original sequence type
Readability Suitable for structured destructuring Suitable for flexible range extraction

Slicing is better suited to cases where start and end positions need to be specified flexibly.

Extended unpacking is better suited to cases where variables need to be assigned directly according to the data structure.

9. Function Return Values and Sequence Unpacking

Python functions can return a tuple so that the caller receives multiple results at once.

For example:

def get_user():
    return "Alice", 25, "Beijing"


name, age, city = get_user()

print(name)
print(age)
print(city)

Here, return actually returns a tuple.

Equivalent to:

def get_user():
    return ("Alice", 25, "Beijing")

When calling the function, the variables on the left can directly unpack the return value.

1. Returning Multiple Calculation Results

def calculate(a, b):
    total = a + b
    difference = a - b
    product = a * b

    return total, difference, product


total, difference, product = calculate(10, 5)

print(total)
print(difference)
print(product)

This design allows a function to return multiple related results at the same time.

2. Ignoring Unneeded Return Values

If only part of the data in the function's return value is needed, a placeholder variable can be used.

def get_user():
    return "Alice", 25, "Beijing"


name, _, city = get_user()

print(name)
print(city)

Here, _ is just an ordinary variable name; by convention, it usually indicates that the current value is not needed.

Note that _ is not a dedicated ignore syntax in Python. After assigning to _, it still stores the corresponding value.

3. Using an Asterisk to Ignore Multiple Values

If you only need the first and last results, you can write it like this:

def get_scores():
    return 90, 85, 88, 95, 92


first, *_, last = get_scores()

print(first)
print(last)

Here, _ receives all the middle elements, but by convention it indicates that these data do not need further processing.

10. Using Sequence Unpacking in Loops

Sequence unpacking is very common in for loops, and is especially suitable for iterating over paired or grouped data.

1. Iterating Over a List of Tuples

users = [
    ("Alice", 25),
    ("Bob", 30),
    ("Charlie", 28)
]

for name, age in users:
    print(name, age)

Each iteration retrieves a tuple, then assigns its two elements to name and age respectively.

2. Using enumerate()

enumerate() produces two-tuples containing an index and a value, so they can be unpacked directly.

fruits = ["Apple", "Banana", "Orange"]

for index, fruit in enumerate(fruits):
    print(index, fruit)

Specify the starting index:

for index, fruit in enumerate(fruits, start=1):
    print(index, fruit)

3. Using zip()

zip() can combine multiple iterables into tuples by position, making it very convenient to use with unpacking.

names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 28]

for name, age in zip(names, ages):
    print(name, age)

Output:

Alice 25
Bob 30
Charlie 28

If you need to check whether multiple iterables have the same length, you can use strict=True from Python 3.10+:

names = ["Alice", "Bob"]
ages = [25, 30]

for name, age in zip(names, ages, strict=True):
    print(name, age)

If the lengths do not match, a ValueError is raised during iteration instead of silently truncating.

By default, zip() stops when the shortest iterable is exhausted.

4. Using extended unpacking to receive loop data

records = [
    ("Alice", 90, 85, 95),
    ("Bob", 80, 88, 92),
    ("Charlie", 95, 90, 98)
]

for name, *scores in records:
    average = sum(scores) / len(scores)

    print(name, average)

This approach suits cases where each record has a fixed set of leading fields but the number of following values may vary.

11. Star unpacking in function calls

In Python, * is used not only for extended unpacking in assignments, but also in function calls, where it expands the elements of an iterable into positional arguments.

For example:

def add(a, b, c):
    return a + b + c


numbers = [10, 20, 30]

result = add(*numbers)

print(result)

Output:

60

It is equivalent to:

result = add(10, 20, 30)

1. Using * to expand positional arguments

def introduce(name, age, city):
    print(name, age, city)


user = ["Alice", 25, "Beijing"]

introduce(*user)

The three elements in the list are passed to the function's three positional parameters.

2. Using ** to expand keyword arguments

The double asterisk ** can expand a dictionary into keyword arguments.

def introduce(name, age, city):
    print(name, age, city)


user = {
    "name": "Alice",
    "age": 25,
    "city": "Beijing"
}

introduce(**user)

Here, the dictionary's keys need to match the parameter names the function accepts.

If there are keys that cannot be matched and the function has no **kwargs to receive extra keyword arguments, a TypeError will be raised.

3. Using * and ** together

def create_user(name, age, city):
    return {
        "name": name,
        "age": age,
        "city": city
    }


args = ["Alice", 25]
kwargs = {"city": "Beijing"}

user = create_user(*args, **kwargs)

print(user)

Output:

{'name': 'Alice', 'age': 25, 'city': 'Beijing'}

You need to distinguish between two usage contexts:

Syntax Assignment context Function call context
* Collects the remaining elements Expands positional arguments
** Not used as an ordinary sequence unpacking target Expands keyword arguments

12. Extended unpacking in assignment context vs. unpacking in function calls

Although both use the asterisk, their semantics differ.

1. Collecting elements during assignment

numbers = [1, 2, 3, 4]

first, *rest = numbers

print(first)
print(rest)

Here, *rest collects the remaining elements into a list.

2. Expanding elements during a function call

def show(a, b, c):
    print(a, b, c)


numbers = [1, 2, 3]

show(*numbers)

Here, *numbers expands the elements of the list into three positional arguments.

3. The two work in opposite directions

This can be understood in terms of data flow:

Extended unpacking in assignment:

multiple elements
    |
    v
collected into one variable
    |
    v
form a list


Asterisk unpacking in function calls:

an iterable object
    |
    v
expand its elements
    |
    v
pass them to multiple positional arguments

Therefore, you cannot assume that they perform the same operation just because the syntax looks similar.

13. Dictionary Merging and Dictionary Unpacking

Python dictionaries also support using ** to expand key-value pairs and create a new dictionary.

For example:

user = {
    "name": "Alice",
    "age": 25
}

profile = {
    **user,
    "city": "Beijing"
}

print(profile)

Output:

{
    'name': 'Alice',
    'age': 25,
    'city': 'Beijing'
}

This syntax can merge multiple dictionaries into a new dictionary.

1. Merging Multiple Dictionaries

default_config = {
    "host": "localhost",
    "port": 8000
}

custom_config = {
    "port": 9000,
    "debug": True
}

config = {
    **default_config,
    **custom_config
}

print(config)

Output:

{
    'host': 'localhost',
    'port': 9000,
    'debug': True
}

If multiple dictionaries contain the same key, the later expanded value overwrites the earlier value.

2. Using the Dictionary Merge Operator

Python 3.9+ also provides the dictionary merge operator |:

config = default_config | custom_config

You can also update in place:

default_config |= custom_config

Both ** dictionary unpacking and | dictionary merging can achieve a merge, but their syntax and use cases are different.

14. Unpacking Iterables and Iterators

The right-hand side of sequence unpacking does not have to be an existing list; it can also be a generator or another iterator.

For example:

numbers = (x * 2 for x in range(4))

a, b, c, d = numbers

print(a, b, c, d)

Output:

0 2 4 6

This shows that unpacking can directly consume data from a generator.

1. Unpacking Consumes the Iterator

numbers = iter([10, 20, 30])

a, b, c = numbers

print(a, b, c)

print(list(numbers))

Output:

10 20 30
[]

The elements in the iterator have already been taken out during unpacking, so the same data cannot be retrieved again afterward.

2. Extended Unpacking Also Consumes the Remaining Elements

numbers = iter([1, 2, 3, 4, 5])

first, *rest = numbers

print(first)
print(rest)

Output:

1
[2, 3, 4, 5]

Extended unpacking needs to collect the remaining elements, so it continues consuming the iterator until iteration ends.

This means:

first, *rest = very_large_generator()

It may load a large number of elements from the generator into memory all at once.

If the data is very large, or the generator may produce data indefinitely, you should not use this syntax casually.

You can instead use tools such as itertools.islice() and next() to retrieve data on demand.

For example:

from itertools import islice

numbers = (x for x in range(1_000_000))

first = next(numbers)
remaining = islice(numbers, 3)

print(first)
print(list(remaining))