user1021726
user1021726

Reputation: 648

Python syntax clarification

Scrolling through the python 2.7 docs I came across this snippet

def fib(n):    # write Fibonacci series up to n
    a, b = 0, 1
    while b < n:
        print a,
        a, b = b, a+b

But I don't understand the last line, and unsure of how I would google for it.

How should I read a, b = b, a+b, or, what does it mean ?

Upvotes: 2

Views: 61

Answers (2)

unutbu
unutbu

Reputation: 880757

Python evaluates the right-hand side of assignments first. It evaluates

b, a+b

from left to right. It then assigns the values to the variables a and b respectively.

So a, b = b, a+b is equivalent to

c = b
d = a+b
a = c
b = d

except that it achieves the result without explicit temporary variables. See the docs on Python's evaluation order.


There is a subtle point here worth examining with an example. Suppose a = 1, b = 2.

a, b = b, a+b

is equivalent to

a, b = 2, 1+2 
a, b = 2, 3

So a gets assign to 2, b is assigned to 3.

Notice that this is not equivalent to

a = b
b = a + b 

Since the first line would assign

a = 2
b = 2 + 2 = 4

Notice that done this (wrong) way, b ends up equal to 4, not 3. That's why it is important to know that Python evaluates the right-hand side of assignments first (before any assignments are made).

Upvotes: 5

StephenTG
StephenTG

Reputation: 2657

It is setting a to b, and b to a + b, without needing an intermediate variable. It could also be accomplished with:

temp = a
a = b
b = temp + b

Upvotes: 4

Related Questions