Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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 ?

share|improve this question

2 Answers 2

up vote 5 down vote accepted

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).

share|improve this answer
    
c is not useful. –  njzk2 Apr 1 at 19:34
    
@njzk2 Not in this case, but there may be cases where it would be, using this sort of assignment. –  StephenTG Apr 1 at 19:35
    
@njzk2: If you assign a = b first, then you've lost the original value of a. So a+b will be (in general) incorrect. Thus, you need a temporary variable c. I would agree that d is not strictly needed however. –  unutbu Apr 1 at 19:38
    
@both : that's right, in fact, c (and d) can be useful in the general case. –  njzk2 Apr 1 at 19:42
    
And I assume the order is important, so that a, b = b, a+b would be something like a = b b = a + b ? –  user1021726 Apr 1 at 19:44

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
share|improve this answer
1  
Very good answer. The only reason you didn't get the voted answer is because I felt the comments and edit on the other answer provided a bit more information, but your answer definitely helped! :) –  user1021726 Apr 2 at 6:51

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.