Is behavior of += intentional for int?

AggieDan04 danb_83 at yahoo.com
Sat Aug 29 16:25:35 EDT 2009


On Aug 29, 8:08 am, Paul McGuire <pt... at austin.rr.com> wrote:
> On Aug 29, 7:45 am, zaur <szp... at gmail.com> 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])
> > True
> > >>> a+=1
> > >>> a
> > 2
> > >>> x[0]
>
> > 1
>
> > I thought that += should only change the value of the int object. But
> > += create new.
> > Is this intentional?
>
> ints are immutable.  But your logic works fine with a mutable object,
> like a list:

Technically, mutability isn't the issue: There's nothing enforcing
that a mutable object HAS to have an __iadd__ method that returns the
same object.



More information about the Python-list mailing list