[Tutor] Understanding code line

Steven D'Aprano steve at pearwood.info
Fri Mar 21 23:40:02 CET 2014


On Fri, Mar 21, 2014 at 01:14:22PM -0400, Gary wrote:
> 
> Pythonists
> 
> I am trying to understand the difference between
> 
> a = b
> b = a + b
>  and
> 
> a,b = b, a+ b

Try to evaluate the code in your head, as if you were the Python 
interpreter. Starting with the first version:

    a = b

This assigns the value to b. So if b was 4, now a is also 4.

    b = a + b

This takes the value of a and the value of b, adds them together, and 
assigns the result to b. Since the previous line set a to b, this is 
exactly the same as:

    b = b + b

so if b was 4, it then becomes 8. The end result of these two lines is 
that b gets doubled each time. The important thing to realise here is 
that a gets its new value, the old value being lost, before it gets 
used to calculate b.

Now for the second version:

    a, b = b, a+b

Here, Python evaluates the right hand side of the = sign first, then 
does the assignments. On the RHS, it evaluates b, and a+b. Then it 
matches them with the names on the LHS, so that a gets the old value of 
b, and b gets the value of (a+b).

The important thing here is that the values on the RHS are calculated 
before the assignments, so it works the way you expect. Most programming 
languages do not allow code like this, so you would have to use a 
temporary variable to get the same result:

    temp = a  # remember the old value of a
    a = b  # set the new value of a
    b = temp + b  # set the new value of b


-- 
Steven


More information about the Tutor mailing list