List unpacking, a feature more broadly known as iterable unpacking, is a powerful and Pythonic way to assign the elements of a sequence (like a list, tuple, or string) to multiple variables in a single line. This is far more concise and readable than accessing each element by its index.
This guide will cover everything from basic unpacking to more advanced techniques using the asterisk (*) operator to capture multiple items and the underscore (_) to discard unwanted items.
Understanding Iterable Unpacking
Iterable unpacking is a form of parallel assignment. When you have an iterable on the right side of an assignment and a comma-separated list of variables on the left, Python pairs them up and assigns each item to its corresponding variable.
Basic Unpacking (Exact Number of Variables)
The simplest form of unpacking requires the number of variables on the left to be exactly equal to the number of items in the list on the right.
Solution:
animals = ['dog', 'cat', 'lion']
dog, cat, lion = animals
print(f"Variable 'dog': {dog}")
print(f"Variable 'cat': {cat}")
print(f"Variable 'lion': {lion}")Output:
Variable 'dog': dog
Variable 'cat': cat
Variable 'lion': lionExtended Unpacking with the Asterisk (*) Operator
Introduced in Python 3, extended unpacking allows one variable, prefixed with an asterisk (*), to be assigned a list of all the items that are "left over" after the other assignments have been made.
Capturing "The Rest" of the Items
This is perfect for when you want to separate the "head" of a list from its "tail."
Solution:
animals = ['dog', 'cat', 'lion', 'wolf', 'tiger']
first_animal, *other_animals = animals
print(f"First animal: {first_animal}")
print(f"Other animals: {other_animals}")Output:
First animal: dog
Other animals: ['cat', 'lion', 'wolf', 'tiger']Capturing Items in the Middle
The starred variable can appear anywhere on the left side, making it incredibly flexible.
Solution:
animals = ['dog', 'cat', 'lion', 'wolf', 'tiger']
first, *middle, last = animals
print(f"First: {first}")
print(f"Middle: {middle}")
print(f"Last: {last}")Output:
First: dog
Middle: ['cat', 'lion', 'wolf']
Last: tigerDiscarding Unwanted Items
Sometimes you only care about a few items in a list and want to ignore the rest.
Discarding Specific Items with _
By convention, the underscore _ is used as a variable name for values that you intend to ignore.
Solution:
animals = ['dog', 'cat', 'lion', 'wolf']
first, _, third, _ = animals
print(f"First animal: {first}")
print(f"Third animal: {third}")Output:
First animal: dog
Third animal: lionDiscarding Multiple Items with *_
You can combine the asterisk * with the underscore _ to discard a variable number of items.
Solution:
animals = ['dog', 'cat', 'lion', 'wolf', 'tiger']
first, second, *_ = animals
print(f"First: {first}")
print(f"Second: {second}")Output:
First: dog
Second: catHandling Mismatched Lengths (ValueError)
If you use basic unpacking and the number of variables does not match the number of items, Python will raise a ValueError.
Example of code causing the error:
animals = ['dog', 'cat', 'lion', 'wolf']
dog, cat = animalsOutput:
Traceback (most recent call last):
File "<main.py>", line 4, in <module>
ValueError: too many values to unpack (expected 2)Solution: the solution is to either match the number of variables exactly or use the asterisk operator (*) to handle the variable-length part of the list.
animals = ['dog', 'cat', 'lion', 'wolf']
dog, cat, *others = animals
print(f"Dog: {dog}")
print(f"Cat: {cat}")
print(f"Others: {others}")Output:
Dog: dog
Cat: cat
Others: ['lion', 'wolf']Conclusion
| Your Goal | The Solution |
|---|---|
| Unpack all items into an equal number of variables. | a, b, c = [1, 2, 3] |
| Get the first item and the rest in a new list. | first, *rest = my_list |
| Get the first and last items and the rest in the middle. | first, *middle, last = my_list |
| Ignore a specific item. | Use the underscore _ as a placeholder: a, _, c = [1, 2, 3]. |
| Ignore multiple items. | Use the starred underscore *_: a, b, *_ = my_list. |
Iterable unpacking is a core feature of Python that makes your code more declarative, readable, and concise. By mastering these patterns, you can write more elegant and effective Python code.