On Aug 29, 8:33 am, Arnaud Delobelle <arno...@googlemail.com> wrote: > ernest <nfdi...@gmail.com> writes: > > Hi, > > > The operator module provides separate functions for > > "in place" operations, such as iadd(), isub(), etc. > > However, it appears that these functions don't really > > do the operation in place: > > > In [34]: a = 4 > > > In [35]: operator.iadd(a, 3) > > Out[35]: 7 > > > In [36]: a > > Out[36]: 4 > > > So, what's the point? If you have to make the > > assignment yourself... I don't understand. > > > Cheers, > > Ernest > > That's because > > a += b > > is executed as: > > a = a.__iadd__(b) > > For immutable objects, (such as integers), a.__iadd__(b) returns a + b > *and then* this value is assigned to a (or rather 'a' is bound to the > value). So for immutables objects, iadd(a, b) is the same as a + b > > For mutable objects (such as lists), a.__iadd__(b) mutates the object > *and then* returns self so that when the assignement is executed, 'a' > will still be bound the the same object. E.g. if a = [1, 2] then > > a += [3] > > will first append 3 to the list and then reassign the list to 'a' (it is > unnecessary in this case but if this step was omitted, the "in place" > operators wouldn't work on immutables types).
This is an excellent explanation. Perhaps, you can submit a documentation patch for the operator module so this doesn't get lost. Raymond -- http://mail.python.org/mailman/listinfo/python-list