On 1/10/2011 11:07 AM, Karim wrote:

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).

Python "interns" certain literal strings - so a 2nd attempt to create 'xyz' will refer back to the original object.

I don't know all the rules - but the following program never prints n:

for n in range(1,10000):
    s = eval("'" + 'wrtnjasdflkasjj'*n + "'")
    t = eval("'" + 'wrtnjasdflkasjj'*n + "'")
    if id(s) != id(t):
        print n; break

whereas if I insert a ";" in the literal the program prints 1!

Also note str() returns the argument object unchanged.


--
Bob Gailer
919-636-4239
Chapel Hill NC

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to