[Tutor] Equality of numbers and Strings
Karim
karim.liateni at free.fr
Mon Jan 10 20:03:20 CET 2011
Many thanks Emile, Bob, Stefan, Wesley!
Now, I see now that the point is more related to implementation details
and optimization instead of a true
property. But it could mistaken people not aware.
Regards
Karim
On 01/10/2011 06:56 PM, Stefan Behnel wrote:
> Karim, 10.01.2011 17:07:
>> 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). 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?
>
> AFAIR, all string literals in a module are interned by the CPython
> compiler, and short strings that look like identifiers are also
> interned (to speed up dictionary lookups, e.g. for function names). So
> you will get identical objects in these cases, although it's not a
> good idea to rely on this as it's an implementation detail of the
> runtime.
>
> And the second thing that you can observe here is that str() never
> copies a string you pass in, which is reasonable behaviour for
> immutable objects.
>
>
>> Thus if I create 2 different instances of string if the string is
>> identical (numerically).
>
> There's no such thing as "numerically identical" strings. It's enough
> to say that they are identical as opposed to equal.
>
> Stefan
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list