Python variable assigning problems...

Robin Koch robin.koch at t-online.de
Fri Dec 11 12:52:48 EST 2015


Am 11.12.2015 um 17:39 schrieb Ian Kelly:
> On Fri, Dec 11, 2015 at 9:24 AM, Robin Koch <robin.koch at t-online.de> wrote:
>> Assigning goes from right to left:
>>
>> x,y=y,x=2,3
>>
>> <=>
>>
>> y, x = 2, 3
>> x, y = y, x
>>
>> Otherwise the assignment x, y = y, x would not make any sense, since x and y
>> haven't any values yet.
>>
>> And the execution from right to left is also a good choice, because one
>> would like to do something like:
>>
>> x = y = z = 0
>>
>> Again, assigning from left to right woud lead to errors.
>
> No, it actually happens left to right. "x = y = z = 0" means "assign 0
> to x, then assign 0 to y, then assign 0 to z." It doesn't mean "assign
> 0 to z, then assign z to y, etc."

Oh. Ok, then, thanks for this correction.
Although it's consequent to use left-to-right precedence it's a little 
counter intuitive in the sense that the rightmost and leftmost objects 
interact. Especially with a background in mathematics. :-)

 > This works:
>
>>>> d = d['foo'] = {}
>>>> d
> {'foo': {...}}
>
> This doesn't:
>
>>>> del d
>>>> d['foo'] = d = {}
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
> NameError: name 'd' is not defined

Good to know! Thank you.

-- 
Robin Koch




More information about the Python-list mailing list