Is behavior of += intentional for int?
Gary Herron
gherron at islandtraining.com
Sat Aug 29 12:12:29 EDT 2009
zaur 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?
>
>
You don't need the (slight) complexity of += to see this. Straight
assignment shows the same behavior.
Try this:
a=1
print id(a)
a=2
print id(a)
The different results from the two prints happens because Python stores
integers 1 and 2 in different locations and the assignments causes a to
refer to one and then the other.
Gary Herron
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090829/7d6abe0f/attachment-0001.html>
More information about the Python-list
mailing list