Why this difference?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Feb 24 19:24:50 EST 2011


On Thu, 24 Feb 2011 13:58:28 +0100, Paul Anton Letnes wrote:

> Den 24.02.11 13.41, skrev n00m:
>> The 1st "False" is not surprising for me. It's the 2nd "True" is a bit
>> hmmm... ok, it doesn't matter ======================
>> Have a nice day!
> 
> I am no expert, but I think python re-uses some integer and string
> objects. For instance, if you create the object int(2) it may be re-used
> later if you have several 2 objects in your code. This is to save some
> memory, or some other performance hack. Don't rely on it.

Absolutely correct.

It can be quite surprising when Python re-uses objects. E.g this 
surprised me:

>>> x, y = "hello world", "hello world"
>>> x == y, x is y
(True, True)

compared to this:

>>> x = "hello world"
>>> y = "hello world"
>>> x == y, x is y
(True, False)


Don't rely on *any* of this, it's subject to change without notice.



-- 
Steven



More information about the Python-list mailing list