Pointers

Thomas Wouters thomas at xs4all.net
Tue Apr 18 16:31:05 EDT 2000


On Tue, Apr 18, 2000 at 05:13:21PM +0200, Klaus-Gerd Meyer wrote:

> Integers and strings with same value are identical, but tuples and list with
> same value are not identical...

Not all integers and strings with the same value are identical, though!

> >>> x = 1
> >>> y = 1
> >>> id(x),id(y)
> (7879224, 7879224)
> >>> x is y            #x and y: same value and identical
> 1

>>> x = 100000
>>> y = 100000
>>> id(x),id(y)   
(135113376, 135230104)
>>> x is y
0
>>> x == y
1

> >>>
> >>> x = "a"
> >>> y = "a"
> >>> id(x),id(y)
> (8041104, 8041104)
> >>> x is y            #x and y: same value and identical
> 1

>>> x = "Ham, spam, eggs, spam, bacon, spam, pate foie gras, spam, saussages and spam"
>>> y = "Ham, spam, eggs, spam, bacon, spam, pate foie gras, spam, saussages and spam"
>>> id(x),id(y)   
(135233304, 135240648)
>>> x is y
0
>>> x == y
1

For strings, you can 'fix' this by using 'intern()':

>>> y = intern("Ham, spam, eggs, spam, bacon, spam, pate foie gras, spam, saussages and spam")
>>> x = intern("Ham, spam, eggs, spam, bacon, spam, pate foie gras, spam, saussages and spam")
>>> id(x),id(y)
(135241592, 135241592)
>>> y == x
1
>>> y is x
1

But you have to force *both* strings this way, interning one isn't enough.
It also doesn't work for integers (i dont think there is a way to do it with
ints) so the best solution is just to not rely on this behaviour.

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list