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.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.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 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: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:
** to unpack a dictionary as keyword arguments:
Merging Dictionaries
The** operator also merges dictionaries:
*args in Function Definitions
When you define a function, *args collects any number of extra positional arguments into a tuple:
*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 afor loop makes iterating over structured data clean and self-documenting:
Common Errors and Fixes
ValueError: too many values to unpack
ValueError: too many values to unpack
More elements than variables on the left side.
ValueError: not enough values to unpack
ValueError: not enough values to unpack
More variables than elements on the right side.
SyntaxError: multiple starred expressions
SyntaxError: multiple starred expressions
Only one
* is allowed per unpacking assignment.