Skip to main content
Packing and unpacking are two sides of the same coin. Packing lets you group several values into a single variable; unpacking lets you pull them apart into individual variables in one line. Together they eliminate temporary variables, make your intent explicit, and unlock the expressive style Python is known for.

Tuple Packing

When you assign multiple comma-separated values to a single variable, Python automatically groups them into a tuple — no parentheses required. This is called packing.
Parentheses are optional but often added for clarity:

Basic Unpacking

Unpacking is the reverse: you extract every element of a collection and assign each one to its own variable, all in a single statement.
This works with any iterable — lists, tuples, strings, and more:
The number of variables on the left must exactly match the number of elements on the right. A mismatch raises a ValueError.

Star Unpacking with *rest

Real data rarely has a fixed length. The * (star) operator lets you capture any number of remaining elements into a list, freeing you from counting elements manually.
You can place the starred variable anywhere — beginning, middle, or end:
You can only use one starred expression per assignment. Using two raises a SyntaxError:

Ignoring Values

Use _ to discard elements you don’t need:

Practical Use Cases

Swapping Variables

The classic swap — no temporary variable needed:
This works because Python evaluates the right-hand side completely before assigning.

Returning Multiple Values from a Function

Functions can return multiple values as a tuple, and callers can unpack them immediately:

Spreading a List into a Function Call

Use * to unpack a list as positional arguments:
Use ** to unpack a dictionary as keyword arguments:

Merging Dictionaries

The ** operator also merges dictionaries:
Later keys override earlier ones, so put your defaults first.

*args in Function Definitions

When you define a function, *args collects any number of extra positional arguments into a tuple:
You can mix regular parameters with *args:

**kwargs in Function Definitions

**kwargs collects any number of extra keyword arguments into a dictionary:

Combining *args and **kwargs

A function that accepts any combination of arguments:

Unpacking in Loops

Unpacking inside a for loop makes iterating over structured data clean and self-documenting:

Common Errors and Fixes

More elements than variables on the left side.
More variables than elements on the right side.
Only one * is allowed per unpacking assignment.

End-to-End Example

The following function parses a CSV line and uses star unpacking to separate the header from the data:
Output: