Reputation: 1445
Can someone explain the difference between:
a, b = 0, 1
while b < 10:
print(b)
a, b = b, a+b
and
a, b = 0, 1
while b < 10:
print(b)
a = b
b = a+b
Upvotes: 2
Views: 74
Reputation: 189809
It's a shorthand to avoid a temporary variable. In many traditional languages, you had to do
tmp = a
a = b
b = b + tmp
Upvotes: 1
Reputation: 198476
Simultaneous:
a = 1
b = 3
a, b = b, a+b
# a: 3; b: 1+3
Sequential:
a = 1
b = 3
a = b
# a: 3; b: 3
b = a+b
# a: 3; b: 3+3
Upvotes: 3
Reputation: 12022
The first one computes all the new values before updating a
and b
. The second one computes and updates a
before computing and updating b
. The second one will give incorrect results because of that.
Here's part of a good talk by Raymond Hettinger where he talks about updating multiple state variables at once.
Upvotes: 2