[Tutor] Equality of numbers and Strings

wesley chun wescpy at gmail.com
Mon Jan 10 18:32:06 CET 2011


On Mon, Jan 10, 2011 at 8:54 AM, bob gailer <bgailer at gmail.com> wrote:

> On 1/10/2011 11:07 AM, Karim wrote:
>
>>
>> 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).
>>
>
> Python "interns" certain literal strings - so a 2nd attempt to create 'xyz'
> will refer back to the original object.
>


i haven't researched all the rules for strings either, but from my
understanding, they're short(er) strings which are used often enough to
warrant interning.

the (current) rule for ints is: range(-5, 257). i say current because before
2.5, it was range(-1, 101). no one bothered to tell me when i updated Core
Python to a 2nd ed. good thing i checked before it went to press! :P

note that floats are also immutable, but they're never interned, so you'll
never get the same one twice unless you're really referring to the same
object. same goes for complex, etc. interning is strictly for commonly-used
small ints and short strings.

cheers,
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110110/d00b034c/attachment.html>


More information about the Tutor mailing list