0

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?

alphanumeric
  • 17,967
  • 64
  • 244
  • 392
  • b =3 #value of b is 3. a = b #value of a is 3. 3+3 is 6. What more do you want? – Sam Apr 18 '16 at 16:38
  • In the second example `b = b+b` because `a` gets the value of `b` one line earlier. In a one-liner it doesn't happen. – ptrj Apr 18 '16 at 16:38
  • when you write a = b you just assign b's value to variable a. – Taylan Apr 18 '16 at 16:39
  • It was quite surprising to find that `a,b=b,a+b` is not just the "one-liner". The syntax changes the way the code is being evaluated. – alphanumeric Apr 18 '16 at 16:40
  • 1
    Note that even the order of the variables is important. See [Tuple unpacking order changes values assigned](http://stackoverflow.com/q/34171348) – Bhargav Rao Apr 18 '16 at 16:41

3 Answers3

6

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.

Niklas B.
  • 92,950
  • 18
  • 194
  • 224
0

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.

Gabriel
  • 1,922
  • 2
  • 19
  • 37
0

( ) 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.

C Panda
  • 3,297
  • 2
  • 11
  • 11