0

I am learning python and I have some question:

What is the difference between

a,b = 0,1
for x in range(100):
    print(a)
    a=b
    b=a+b

and

a,b = 0,1
for x in range(100):
    print(a)
    a,b = b, a+b

First one gives bad result, but why?

Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63
pablos91
  • 39
  • 6

1 Answers1

1

Because you first set a = b, your new b will have the value of twice the old b. You overwrite a to early. A correct implementation should use a temporary variable t:

a,b = 0,1
for x in range(100):
print(a)
    t=a
    a=b
    b=t+b

This is basically what you do by using sequence assignment.

In your original code you have:

a,b = 0,1
for x in range(100):
    print(a)
    a=b # a now is the old b
    b=a+b # b is now twice the old a so b'=2*b instead of b'=a+b

So this would result in jumping by multiplying with two each time (after first loading in 1 into a the first step).


An equivalent problem is the swap of variables. If you want a to take the value of b and vice versa, you cannot write:

#wrong swap
a = b
b = a

Because you lose the value of a after the first assignment. You can use a temporary t:

t = a
a = b
b = t

or use sequence assignment in Python:

a,b = b,a

where a tuple t = (b,a) is first created, and then assigned to a,b.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555