This is my first question and I started to learn Python. Is there a difference between:
a, b = b, a + b
and
a = b b = a + b
When you write it in below example it shows different results.
def fib(n): a, b = 0, 1 while a < n: print(a, end=' ') a, b = b, a + b print() fib(1000)
and
def fib(n): a, b = 0, 1 while a < n: print(a, end=' ') a = b b = a + b print() fib(1000)
Let's grok it. a, b = b, a + b. It's a tuple assignment, means (a, b) = (b, a + b) , just like (a, b) = (b, a) Start from a quick example: a, b = 0, 1 #equivalent to (a, b) = (0, 1) #implement as a = 0 b = 1.
When the numbers match, it's a one-to-one unpacking. It appears that a, b = b, a involves the one-to-one unpacking. However, it turns out that Python uses an optimized operation (i.e., ROT_TWO ) to swap the references on a stack. Such swapping happens when three variables are involved.
The 'ab' is the mode for open, i.e. append to binary.
For mutable types such as list , the result of a = b[:] will be identical to a[:] = b , in that a will be a shallow copy of b ; for immutable types such as tuple , a[:] = b is invalid. For badly-behaved user-defined types, all bets are off.
In a, b = b, a + b
, the expressions on the right hand side are evaluated before being assigned to the left hand side. So it is equivalent to:
c = a + b a = b b = c
In the second example, the value of a
has already been changed by the time b = a + b
is run. Hence, the result is different.
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