Skip to main content
Packing and unpacking are two of Python’s most expressive convenience features. Packing lets you bundle multiple values into a single tuple in one assignment, while unpacking lets you extract values from any iterable — tuple, list, string, or dictionary — directly into named variables on a single line. Together, these features make your code cleaner, reduce intermediate variables, and enable elegant patterns in loops and function signatures.

Tuple Packing

When you assign multiple values to a single variable without brackets, Python automatically groups them into a tuple:
No parentheses are required — the commas do the packing.

Basic Unpacking

Unpacking is the reverse: Python extracts elements from a collection and assigns them to individual variables in one step:
The number of variables on the left must exactly match the number of elements on the right. A mismatch raises a ValueError.

Extended Unpacking with *

When you only care about specific elements and want to capture the rest as a list, prefix one variable with * (a starred expression):
You can place the starred variable anywhere — at the start, end, or middle:
You can use only one starred expression per assignment. Two starred variables in the same statement causes a SyntaxError because Python cannot determine where one group ends and the other begins.

Dictionary Unpacking with **

For dictionaries, the double-star ** operator unpacks key-value pairs. This is most commonly used to merge dictionaries:
Keys from later dictionaries overwrite those from earlier ones, making this pattern great for applying user preferences on top of defaults.

Unpacking in Loops

Unpacking shines in loops, turning tuple-heavy iterations into readable, named variables.

Iterating Over a List of Tuples

Using enumerate()

enumerate() yields (index, item) pairs — perfect for unpacking:

Iterating Over Dictionary Items

Common Errors and Fixes

The iterable has more elements than you have variables.
You have more target variables than elements in the iterable.
Python allows only one * variable per assignment statement.