Lesson explanation
By the end of this lesson, you can:
(number, record) values while iterating.In Python, unpacking assigns elements from a sequence to several variables at once:
service, region = ("api", "eu")The number of targets must match the number of elements, unless one target is starred. A star collects the remaining elements into a list:
first, *middle, last = [2, 4, 6, 8]Here, middle is [4, 6]. It can also be empty when the input contains just two items. Only one starred target is allowed in a single unpacking assignment.
Multiple assignment also makes swapping simple: a, b = b, a evaluates the right side before assigning the names.
Unpacking works naturally with for loops: for name, score in pairs: gives useful names to the two parts of every pair. You can also unpack a pair inside enumerate() using for number, (name, score) in enumerate(pairs, start=1):. This is a good fit when the record itself contains several fields but you also need its position.
host, port = ("db.internal", 5432)
print(f"Connect: {host}:{port}")Output:
Connect: db.internal:5432The two tuple elements are assigned to the two names, in order.
front = "blue"
back = "orange"
front, back = back, front
print(f"Front: {front}, back: {back}")Output:
Front: orange, back: blueBoth old values are captured before either name changes.
measurements = [10, 12, 14, 16, 20]
first, *middle, last = measurements
print(first)
print(middle)
print(last)Output:
10
[12, 14, 16]
20The starred target always receives a list, even when it has no values.
checks = [("lint", True), ("tests", False)]
for number, (name, passed) in enumerate(checks, start=1):
print(f"{number}. {name}: {passed}")Output:
1. lint: True
2. tests: FalseThe outer pair holds (number, record); the inner pair splits the record into (name, passed).
| Goal | Python |
|---|---|
| Unpack two entries | left, right = pair |
| Swap names | left, right = right, left |
| Capture middle entries | first, *middle, last = values |
| Unpack each pair | for key, value in pairs: |
| Number and unpack pairs | for n, (key, value) in enumerate(pairs, 1): |
ValueError.enumerate(pairs) returns (index, pair), not three separate values.