Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

Unpacking in Python is the process of extracting elements from an iterable (such as a tuple, list, or string) or a mapping (such as a dictionary) and assigning them to a sequence of variables. While the right-hand side (RHS) expression is fully evaluated before any assignment occurs, the actual binding to the left-hand side (LHS) variables is executed sequentially from left to right. Consequently, unpacking is not strictly atomic; if an assignment fails mid-sequence (e.g., due to a property setter raising an exception), the preceding assignments will have already been applied and will persist.

Basic Iterable Unpacking

In standard unpacking, the number of variables on the LHS must exactly match the length of the iterable on the RHS.

# Tuple unpacking
a, b, c = (1, 2, 3)


# List unpacking
x, y = [10, 20]


# String unpacking (strings are iterables of characters)
char1, char2, char3 = "foo"
If the lengths do not match, Python raises a ValueError (too many values to unpack or not enough values to unpack). When a dictionary is unpacked directly into a sequence of variables, Python iterates over the dictionary and extracts its keys, not its values.

# Dictionary unpacking extracts keys
k1, k2 = {'x': 1, 'y': 2}

# k1: 'x'

# k2: 'y'
Because the RHS is fully evaluated before assignment, unpacking allows for direct variable swapping without requiring a temporary variable. At the bytecode level, modern Python (3.11+) handles this using the SWAP instruction.
a, b = b, a

Nested Unpacking

Unpacking can mirror the nested structure of the RHS data. By grouping LHS variables in parentheses or brackets, Python recursively unpacks the inner iterables based on the defined structural alignment.

# Nested unpacking
a, (b, c) = [1, [2, 3]]

# a: 1

# b: 2

# c: 3

Unpacking in for Loops

Unpacking is natively supported in for loop declarations, allowing iteration over sequences of iterables. The loop unpacks each inner iterable into the specified variables on every iteration.

# Unpacking a list of tuples
for x, y in [(1, 2), (3, 4)]:
    pass


# Unpacking dictionary items (key-value pairs)
my_dict = {'a': 10, 'b': 20}
for key, value in my_dict.items():
    pass

Extended Iterable Unpacking (PEP 3132)

Extended unpacking introduces the single asterisk (*) operator, known as the “catch-all” or “splat” operator. When applied to a variable on the LHS, it captures all elements from the iterable that are not assigned to mandatory variables, returning them as a list. Only one starred expression is permitted per assignment target.

# Capturing the tail
first, *rest = [1, 2, 3, 4, 5]

# first: 1

# rest: [2, 3, 4, 5]


# Capturing the head
*head, last = (10, 20, 30)

# head: [10, 20]

# last: 30


# Capturing the middle
first, *middle, last = "python"

# first: 'p'

# middle: ['y', 't', 'h', 'o']

# last: 'n'
If there are no remaining elements to capture, the starred variable evaluates to an empty list ([]).

Unpacking Generalizations (PEP 448)

Python extends unpacking beyond assignment statements, allowing the * and ** operators to unpack iterables and mappings directly into other data structure literals or function arguments. Iterable Unpacking (*) The * operator unpacks the contents of an iterable into a new sequence literal (list, tuple, or set).
list_one = [1, 2]
list_two = [3, 4]


# Unpacking into a new list literal
combined_list = [*list_one, *list_two]

# combined_list: [1, 2, 3, 4]


# Unpacking into a set literal
unique_elements = {*list_one, *[2, 3, 5]}

# unique_elements: {1, 2, 3, 5}
Mapping Unpacking (**) The double asterisk (**) operator unpacks key-value pairs from a mapping object (like a dict) into a new dictionary literal. If duplicate keys exist, the value from the rightmost unpacked mapping overwrites previous values.
dict_one = {'a': 1, 'b': 2}
dict_two = {'b': 99, 'c': 3}


# Unpacking into a new dictionary literal
combined_dict = {**dict_one, **dict_two}

# combined_dict: {'a': 1, 'b': 99, 'c': 3}

Function Argument Unpacking

The same operators are used to unpack data structures into function arguments during a call. * unpacks an iterable into positional arguments, and ** unpacks a mapping into keyword arguments.
def process_data(x, y, z):
    pass

args = (10, 20, 30)
kwargs = {'x': 10, 'y': 20, 'z': 30}


# Unpacking iterable into positional arguments
process_data(*args)


# Unpacking mapping into keyword arguments
process_data(**kwargs)
Master Python with Deep Grasping Methodology!Learn More