A file contains a header, several measurements and a footer.
What You Need to Understand
Extended unpacking uses a starred target to gather leftover elements into a list. An underscore is only a conventional name for ignored information: Python still stores a value in it.
When to Use It
A file contains a header, several measurements and a footer.
Step-by-Step Python Example
records = ["start", 10, 20, 30, "end"]
header, *measurements, footer = records
print(header)
print(measurements)
print(footer)
How the Example Works
The first and last items bind to named variables; the middle items become a new list.
Example Output
start
[10, 20, 30]
end
3 [5, 7, 9]
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
values = [3, 5, 7, 9]
first, *remaining = values
print(first, remaining)
Important Behavior and Edge Cases
The starred target receives a list even if the input is a tuple. You cannot use more than one starred target in a single assignment.
Try It Yourself
Unpack a five-item list into first item, middle items and last item.
Common Beginner Mistakes
- The starred target receives a list even if the input is a tuple. You cannot use more than one starred target in a single assignment.
- Assuming every sequence operation modifies the original data or that a tuple makes nested mutable objects immutable.
Key Takeaways
- Extended unpacking uses a starred target to gather leftover elements into a list.
- The first and last items bind to named variables; the middle items become a new list.
- The starred target receives a list even if the input is a tuple.