-2

What is the difference between these two python code?.i thought both are same but the output i am getting is different


    def fibonacci(num):
        a=1
        b=1
        series=[]
        series.append(a)
        series.append(b)
        for i in range(1,num-1):
            series.append(a+b)
            #a,b=b,a+b
            a=b
            b=a+b
            
            
            
        return series
    print(fibonacci(10))


    def fibonacci(num):
        a=1
        b=1
        series=[]
        series.append(a)
        series.append(b)
        for i in range(1,num-1):
            series.append(a+b)
            a,b=b,a+b
            #a=b
            #b=a+b
            
            
            
        return series
    print(fibonacci(10))

norok2
  • 25,683
  • 4
  • 73
  • 99
  • Does this answer your question? [Is there a standardized method to swap two variables in Python?](https://stackoverflow.com/questions/14836228/is-there-a-standardized-method-to-swap-two-variables-in-python) – norok2 Sep 09 '22 at 14:21
  • thanks for the answer.But i want to know about the memory assignment part and why it is giving me different output – Zeusthunder1 Sep 09 '22 at 14:32
  • hey thanks for the all the answers i got the full explanation below given by @M K – Zeusthunder1 Sep 09 '22 at 14:48

2 Answers2

1

In the first method

a=b
b=a+b

is an incorrect way of swapping, when you say a=b you have lost the value of a, so b=a+b is the same as b=b+b, which is not what you want.

Another way to achieve an equivalent result to this approach, a,b = b,a+b, is by using a temporary variable to store a, as follows:

tmp = a
a = b
b = tmp + b 
-1

The issue here is about storing the values you are calculating, on the first snippet you are saying a+b only on the second snippet you are saying b =a+b. The value of b is changing when you say b = a+b.

Hope my explanation is understandable.You are re-assigning the value of b o the first snippet (b=a+b)