3

I was looking at the Python Manual and found this snippet for a Fibonacci-Number generator:

def fib(n):    # write Fibonacci series up to n
    a, b = 0, 1
    while b < n:
        print(b, end=' ')
        a, b = b, a+b
    print()

The output is dependent on n and returns a valid Fibonacci sequence.

If you remodel this to use the variables "a" and "b" seperately like so:

def fib(n):    # write Fibonacci series up to n
    a = 0
    b = 1
    while b < n:
        print(b, end=' ')
        a = b
        b = a+b
    print()

then it will print a number sequence that increments by the power of 2 (e.g. 1, 2, 4, 8, 16 and so on).

So I was wondering why that happens? What is the actual difference between the two uses of variables?

waffl3head
  • 128
  • 1
  • 1
  • 5
  • Yes. It's a duplicate. Didn't find the other entry with the search function prior to creating this question. – waffl3head Apr 15 '14 at 13:34

2 Answers2

12

Doing:

a, b = b, a+b

is equivalent to:

temp = a
a = b
b += temp

It lets you simultaneously do two calculations without the need of an intermediate/temporary variable.

The difference is that in your second piece of code, when you do the second line b = a+b, you have already modifed a in the previous line which is not the same as the first piece of code.

Examples

>>> a = 2
>>> b = 3
>>> a,b
2 3
>>> a,b = b,a
>>> a,b
3 2

On the other hand, if you use the second approach shown in your question:

>>> a = 2
>>> b = 3
>>> a,b
2 3
>>> a = b
>>> b = a
>>> a,b
3 3
Community
  • 1
  • 1
sshashank124
  • 31,495
  • 9
  • 67
  • 76
4

In

    a, b = b, a+b

the right-hand expressions are evaluated first, and their results are assigned to a and b. This is similar to the following:

    _new_a = b
    _new_b = a+b
    a = _new_a
    b = _new_b

On the other hand, in

    a = b
    b = a+b

you are modifying a before adding it to b. This is equivalent to

    a, b = b, b+b

which explains where the powers of two are coming from.

NPE
  • 486,780
  • 108
  • 951
  • 1,012