Tuple Packing
When you assign multiple values to a single variable without brackets, Python automatically groups them into a tuple:Basic Unpacking
Unpacking is the reverse: Python extracts elements from a collection and assigns them to individual variables in one step: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 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:
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
ValueError: too many values to unpack
ValueError: too many values to unpack
The iterable has more elements than you have variables.
ValueError: not enough values to unpack
ValueError: not enough values to unpack
You have more target variables than elements in the iterable.
SyntaxError: multiple starred expressions
SyntaxError: multiple starred expressions
Python allows only one
* variable per assignment statement.