[Tutor] operator order

Hugo Arts hugo.yoshi at gmail.com
Thu Jan 31 23:53:22 CET 2013


On Thu, Jan 31, 2013 at 8:20 PM, Danny Yoo <dyoo at hashcollision.org> wrote:

> On Thu, Jan 31, 2013 at 11:36 AM, heathen <godsofliberty at lavabit.com>
> wrote:
> > why is this:
> >
> >>>> d *= 3 + 4
>
>
> The gory details about how Python understands this expression can be found
> in:
>
>
> http://docs.python.org/3/reference/simple_stmts.html#augmented-assignment-statements
>
> Technically, "3 + 4" is the "expression list" part of the statement,
> so it gets evaluated.  Then it does the multiplication of the target
> (d) and the value of the expression list (7).
>
>
The docs really hit it with that "similar but not exactly equal" phrase.
Augmented assignment is one of those things that is sort-of-but-not-really
equivalent, so it can really bite you in the ass. I recently encountered
this little gem on:

>>> a = ([], [])
>>> a[0] += [1]

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    a[0] += [1]
TypeError: 'tuple' object does not support item assignment
>>> a
([1], [])
>>>

tuples are immutable, but lists *do* support in-place modification. And
thus we get an operation that both fails and succeeds at the same time..
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130131/421b8821/attachment.html>


More information about the Tutor mailing list