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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With