2

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 ?

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

6 Comments

@njzk2 Not in this case, but there may be cases where it would be, using this sort of assignment.
@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.
@both : that's right, in fact, c (and d) can be useful in the general case.
And I assume the order is important, so that a, b = b, a+b would be something like a = b b = a + b ?
No. Everything happens at the same time.
|
4

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

1 Comment

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! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.