list to table

Alf P. Steinbach alfps at
Fri Nov 6 01:23:27 CET 2009

* Jon Clements:
> I read the OP as homework (I'm thinking Scott did as well),

Sorry. Need to recalibrate that neural network. Back-propagation initiated... 
Done! :-)

> however,
> your code would be much nicer re-written using collections.defaultdict
> (int)... which I don't think is giving anything away...


This sent me searching everywhere, because the documentation of '+=' and other 
"augmented assignment statements" says

   "The target is only evaluated once.",

like in C++, which implies a kind of reference to mutable object.

I couldn't immediately see how subscription could apparently return a reference 
to mutable int object in Python in a way so that it worked transparently (the 
idiom in C++).

However, it worked to replace collections.defaultdict with a class overriding 
__getitem__ and __setitem__, so I guess that's how it works, that in this case 
'+=' is simply translated like 'x += n' -> 'temp = x; x = temp + n'.

Is this a correct understanding, and if so, what exactly does the documentation 
mean for the general case?


def foo():
     print( "foo" )
     d = dict(); d[43] = 666
     return d

def bar():
     print( "bar" )
     return 43;

foo()[bar()] += 1



so here it's not translated like 'foo()[bar()] = foo()[bar()] + 1' but evidently 
more like 'a = foo(); i = bar(); a.__setitem__(i, a.__getitem__(i) + 1)'?

If so, is this behavior defined anywhere?

I did find discussion (end of §6.2 of the language reference) of the case where 
the target is an attibute reference, with this example:

class A:
     x = 3    # class variable
a = A()
a.x += 1     # writes a.x as 4 leaving A.x as 3


Cheers, & thanks,

- Alf

More information about the Python-list mailing list