Is behavior of += intentional for int?

Günther Dietrich gd_usenet at
Sat Aug 29 15:23:20 CEST 2009

zaur <szport at> wrote:

>Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39)
>[GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
>Type "copyright", "credits" or "license()" for more information.
>>>> a=1
>>>> x=[a]
>>>> id(a)==id(x[0])
>>>> a+=1
>>>> a
>>>> x[0]
>I thought that += should only change the value of the int object. But
>+= create new.
>Is this intentional?

An integer variable contains the reference (ID) to an (immutable) 
integer object; it doesn't contain the value itself. So, when you assign 
a new value to an integer variable, it will contain the reference to the 
object containing the new value, afterwards.

If you assign an integer variable to a list element, this reference will 
be written into the list. The assignment of a new value to the integer 
variable will create a new integer object, containing the new value, and 
put the reference to it into the integer variable.
The reference to the object with the old value, that is stored in the 
list, won't be touched.

In fact, it is a result of integers in python being immutable.

Best regards,


More information about the Python-list mailing list