Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between writing something on one line and on several lines

Tags:

python

Where is the difference when I write something on one line, seperated by a , and on two lines. Apparently I do not understand the difference, because I though the two functions below should return the same.

def fibi(n):
    a, b = 0, 1
    for i in range(n):
        a, b = b, a + b
    return a

print(fibi(6))
> 8 # expected result (Fibonacci)

But

def fibi(n):
    a, b = 0, 1
    for i in range(n):
        a = b
        b = a + b 
    return a


print(fibi(6))
> 32 
like image 982
Stophface Avatar asked Dec 03 '15 15:12

Stophface


1 Answers

This is because of Python's tuple unpacking. In the first one, Python collects the values on the right, makes them a tuple, then assigns the values of the tuple individually to the names on the left. So, if a == 1 and b == 2:

   a, b = b, a + b
=> a, b = (2, 3)
=> a = 2, b = 3

But in the second example, it's normal assignment:

   a = b
=> a = 2
   b = a + b
=> b = 4
like image 151
Daniel Roseman Avatar answered Oct 14 '22 16:10

Daniel Roseman