On 29 авг, 23:03, Steven D'Aprano <st...@remove-this- cybersource.com.au> wrote: > On Sat, 29 Aug 2009 11:11:43 -0700, zaur wrote: > > I thought that int as object will stay the same object after += but with > > another integer value. My intuition said me that int object which > > represent integer value should behave this way. > > If it did, then you would have this behaviour: > > >>> n = 3 # bind the name n to the object 3 > >>> saved_id = id(n) # get the id of the object > >>> n += 1 # add one to the object 3 > >>> assert n == 4 # confirm that it has value four > >>> assert id(n) == saved_id # confirm that it is the same object > >>> m = 3 # bind the name m to the object 3 > >>> print m + 1 # but object 3 has been modified > > 5 > > This would be pretty disturbing behaviour, and anything but intuitive. > > Fortunately, Python avoids this behaviour by making ints immutable. You > can't change the object 3 to have any other value, it will always have > value three, and consequently n+=1 assigns a new object to n. > > -- > Steven
This behavior is because small integers are cached internally. See Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> a=1 >>> c=1 >>> d=10000 >>> e=10000 >>> id(a),id(c),id(d),id(e) (16793992, 16793992, 17067336, 17067276) -- http://mail.python.org/mailman/listinfo/python-list