Beginner's assignment question

Schizoid Man schiz at lon.don
Sun Mar 2 05:25:49 EST 2008


Lorenzo Gatti wrote:
> On Mar 1, 3:39 pm, Schizoid Man <sc... at lon.don> wrote:
>> As in variable assignment, not homework assignment! :)
>>
>> I understand the first line but not the second of the following code:
>>
>> a, b = 0, 1
>> a, b = b, a + b
>>
>> In the first line a is assigned 0 and b is assigned 1 simultaneously.
>>
>> However what is the sequence of operation in the second statement? I;m
>> confused due to the inter-dependence of the variables.
> 
> The expressions of the right of the assignment operator are evaluated
> before assigning any new values, to the destinations on the left side
> of the assignment operator.
> So substitutig the old values of a and b the second assignment means
> 
> a, b = 0, 0 + 1
> 
> Simplifying the Python Reference Manual ("6.3 Assignment Statements")
> a little :
> 
> assignment_stmt ::= target_list "="+ expression_list
> 
> An assignment statement evaluates the expression list (remember that
> this can be a single expression or a comma-separated list, the latter
> yielding a tuple) and assigns the single resulting object to each of
> the target lists, from left to right.
> 
> [...]
> 
> WARNING: Although the definition of assignment implies that overlaps
> between the left-hand side and the right-hand side are `safe' (for
> example "a, b = b, a" swaps two variables), overlaps within the
> collection of assigned-to variables are not safe! For instance, the
> following program prints "[0, 2]":
> 
> x = [0, 1]
> i = 0
> i, x[i] = 1, 2
> print x
> 
> Lorenzo Gatti

Thank you for the explanation. I guess my question can be simplified as:

First step: a, b = 0, 1
No problem here as a and b are assigned values.

Second step: a, b = b, a + b

Now my question is does b become a + b after a becomes 1 or while a 
stays at 0?

As the assignment occurs simultaneously I suppose the answer is while a 
stays at 0.

Thank you.



More information about the Python-list mailing list