[Tutor] Equality of numbers and Strings

Emile van Sebille emile at fenx.com
Mon Jan 10 17:51:10 CET 2011


On 1/10/2011 8:07 AM Karim said...
>
> Hello All,
>
> I am not a beginner in Python language but I discovered a hidden
> property of immutable elements as Numbers and Strings.
>
> s ='xyz'
>  >>> t = str('xyz')
>
>  >>> id(s) == id(t)
> True
>
> Thus if I create 2 different instances of string if the string is
> identical (numerically).

well, not predictably unless you understand the specifics of the 
implementation you're running under.


 >>> from string import letters
 >>> longstring = letters*100
 >>> otherstring = letters*100
 >>> id(longstring)
12491608
 >>> id (otherstring)
12100288
 >>> shortstring = letters[:]
 >>> id(letters)
11573952
 >>> id(shortstring)
11573952
 >>>


> I get the same object in py db. It could be evident but if I do the same
> (same elements) with a list it
> will not give the same result. Is-it because of immutable property of
> strings and numbers?
>

It has to do with Interning -- see eg
   http://docs.python.org/library/functions.html#intern

Generally, the shorter strings are interned to speed up dictionary 
access.  At this point, I'd characterize the coincidence of id()s as 
more of an implementation detail side effect than anything else.

Emile



More information about the Tutor mailing list