On Saturday 14 April 2007, James Stroud wrote: > I think that after a += 1, a memory location with a 6 is created and now > a points to that because += has assignment buried in it.
Bingo. a+=1 will (basically) translate to either "a=a.__iadd__(1)" or "a=a.__add__(1)" depending on whether __iadd__ is defined of not. >>> '__iadd__' in dir(5) False >>> '__add__' in dir(5) True So therefore "a+=1" becomes "a=a.__add__(a, 1)" That make is relatively obvious that a '6' would be created and assigned back to a. You can have some fun with this using the 'is' operator. Remember that 'is' compares objects and not values. So different objects can be equal, but aren't the same. Thus: >>> a=[1,2,3] >>> b=[1,2,3] >>> a == b True >>> a is b False To demonstrate the idea of name binding: >>> a=500 >>> b=500 >>> a == b True >>> a is b False >>> b=a >>> a is b True So typing the literal '500' creates an integer object with the value 500. By typing it twice, two different objects of identical value are created and "put in" two variables. However, by assigning one from the other, the same object (created by the literal '500') is assigned to both variables. This is why Python calls assignments "bindings"; you're realling just binding the object from the right side to the name on the left. For confusion's sake, here's what happens if you use smaller numbers: >>> a=1 >>> b=1 >>> a is b True >>> 3-2 is a True That happens because CPython (a particular and very common implementation of Python) pre-creates objects for all small integers (something like <=100). This saves memory, because all values of '1' are the same! So the literal '1' simply gets a reference to the existing object of value '1', rather than creating a new one (like the literal '500' does). The same is also true for strings with len<=1. -- http://mail.python.org/mailman/listinfo/python-list