(a,b) = (0,1)
(a,b) = (b,b+a)
Print(a)
Print(b)
Output
1
1
Asked
Active
Viewed 37 times
-4

Klaus D.
- 13,874
- 5
- 41
- 48
-
because a is 0. – hjpotter92 Sep 03 '20 at 07:56
-
1BTW it is lowercase `print`. – Klaus D. Sep 03 '20 at 07:57
-
Because `(b,b+a)` gets *evaluated first* before the destructing assignment occurs. – juanpa.arrivillaga Sep 03 '20 at 07:57
-
`a` is 0, `b` is 1, so `(b, b+a)` evaluates to `(1, 1+0)` i.e. `(1, 1)`. Assigning `(1, 1)` to `(a, b)` makes both `a` and `b` 1. – CherryDT Sep 03 '20 at 08:03
1 Answers
2
because the assignement with destructuring tuple is done "simultaneously"
When line 2 begins, a
is zero and b
is 1.
The right-hand side (b,b+a)
gets both values calculated with these prior values (it's just one tuple calculated). This gives (1,1)
.
Then, only then, the assignment to the left.-hand side occurs, and so a
and b
become both 1
.
Maybe you thought that, because we reassign a as 1
in the first position of tuple on line 2, then it would be this value used on the second position of the tuple.
This is not the case.
This syntax allows for instance to swap variable without creating a temporary variable: (a, b) = (b,a)
.
If you rely on the order of assignements, then we need to write two sequential assignments:
(a,b) = (0,1)
a = b
b = b+a
print(a)
print(b)

Pac0
- 21,465
- 8
- 65
- 74