why does this happen?

Greg Jorgensen gregj at pobox.com
Sun Feb 11 19:00:49 EST 2001


In article <r%Eh6.225470$f36.9097034 at news20.bellglobal.com>,
dan at eevolved.com wrote:
> key = 0
> dict = {0:''}
> key = dict[key] = "__0"
> print key
> >>> __0
> print dict
> >>> {9: '', '__9': '__9'}

** I think you meant {0: '', '__0': '__0'}

>
> It doesn't do it from right to left like in c? Obviously not. Does
anyone
> know why?

In C assignment is an expression: the value of the expression a=1 is 1.
In Python, assignment is not an expression: print a=1 is an error.
Python allows assignment to several variables "simultaneously" (that's
what the Python Tutorial says) with the form a = b = 1. I don't see
anything in the Language Reference that says what order the assignments
are actually carried out, but from your experiment and my own it looks
like a = b = 1 is equivalent to:

a = 1
b = 1

In other words, the rightmost expression is assigned to each lvalue in
left-to-right order. But unless the order of assignment is explicitly
specified in the language spec you should not rely on it.

Perhaps a clearer example is:

>>> i = 0
>>> t = [0,0]
>>> i = t[i] = 1
>>> i
1
>>> t
[0,1]


--
Greg Jorgensen
Portland, Oregon, USA
gregj at pobox.com


Sent via Deja.com
http://www.deja.com/



More information about the Python-list mailing list