[Tutor] Equality of numbers and Strings
Stefan Behnel
stefan_ml at behnel.de
Mon Jan 10 18:56:35 CET 2011
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
More information about the Tutor
mailing list