Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python a, b = b, a +b

Tags:

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) 
like image 739
Ante Avatar asked Feb 24 '14 14:02

Ante


People also ask

What does a b/b a/b mean in Python?

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.

How the a B and B A works in Python?

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.

What does AB mean in Python?

The 'ab' is the mode for open, i.e. append to binary.

What is the difference between AB and AB in Python?

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.


1 Answers

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.

like image 169
isedev Avatar answered Oct 20 '22 04:10

isedev