Reputation: 19349
While working with Fibonacci sequence:
a = 1
b = 3
a, b = b, a + b
print a, b
This properly results to a = 3
and b = 4
Now if I would re-code it as:
a = 1
b = 3
a = b
b = a + b
print a, b
the resulting variable b
is 6
instead of 4
.
What happens "behind of scenes" when one-liner a, b = b, a + b
is used?
Upvotes: 0
Views: 90
Reputation: 3415
(
)
don't make the sequence a tuple, rather ,
s do.
a, b = b, a + b # => (a,b) = (a, a+b) if written with brackets
So, it's standard tuple unpacking. But the thing with names a
and b
on the lest is they are names of different objects now, namely those known as b
and result of a+b
previously. This behavior is partly due to the fact that variable names in python are names, not boxes,like in C, that store values.
Upvotes: 0
Reputation: 1942
You said
b = 3
and then
a = b
and then
b = a + b
which is the same as
b = b + b
or, in other words,
b = 3 + 3
,
so b = 6
.
The first one is like a, b = 3, 1 + 3
or a, b = 3, 4
so b = 4
.
Upvotes: 0
Reputation: 95328
This is a combination of tuple packing and sequence unpacking. It is parsed the same way as
(a, b) = (b, a + b)
The tuple on the right side is evaluated before the assignment, which is why the "old" values are used.
Upvotes: 6