Concept Flow - Tuple unpacking
Create tuple with values
Assign tuple to variables
Unpack values into variables
Use variables separately
Tuple unpacking takes a tuple and assigns each value to a separate variable in one step.
Jump into concepts and practice - no test required
point = (3, 7) x, y = point print(x) print(y)
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Create tuple 'point' | point = (3, 7) | point holds (3, 7) |
| 2 | Unpack tuple into x and y | x, y = point | x = 3, y = 7 |
| 3 | Print x | print(x) | 3 |
| 4 | Print y | print(y) | 7 |
| 5 | End | No more code | Execution stops |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| point | undefined | (3, 7) | (3, 7) | (3, 7) |
| x | undefined | undefined | 3 | 3 |
| y | undefined | undefined | 7 | 7 |
Tuple unpacking syntax: x, y = (value1, value2) Assigns each tuple element to variables in order. Number of variables must match tuple size. Useful for clean, readable code when working with tuples.
a, b = (1, 2)a, b = (1, 2) assigns the first value 1 to variable a and the second value 2 to variable b.point = (4, 5) x, y = point print(x + y)
(4, 5) is unpacked into x = 4 and y = 5.x + y gives 4 + 5 = 9.data = (1, 2, 3) a, b = data print(a, b)
data has 3 values but only 2 variables a and b are on the left side.points = [(1, 2), (3, 4), (5, 6)]
total_x = 0
total_y = 0
for point in points:
# Fill in unpacking here
total_x += x
total_y += y
print(total_x, total_y)point is a tuple like (1, 2). To access x and y, unpack it into variables x and y.x, y = point. This assigns the first element to x and second to y for each tuple in the list.