Python variable assigning problems...

Ian Kelly ian.g.kelly at gmail.com
Fri Dec 11 11:39:17 EST 2015


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



More information about the Python-list mailing list