Question about 'None'
Steven Bethard
steven.bethard at gmail.com
Thu Jan 27 16:37:10 EST 2005
Francis Girard wrote:
>>>>a = "10"
>>>>b = 10
>>>>a > b
> True
>
>>>>b > a
> False
>
>>>>id(a)
> 1077467584
>
>>>>id(b)
> 134536516
Just to thoroughly explain this example, the current CPython
implementation says that numbers are smaller than everything but None.
The reason you get such a small id for 'b' is that there is only one 10
object (for efficiency reasons):
py> 10 is 5 + 5
True
py> 99 is 50 + 49
True
py> 100 is 50 + 50
False
Note that there may be many different instances of integers 100 and
above (again, in the current CPython implementation). So to get an
integer id above a string id, your integer must be at least 100:
py> a = "100"
py> b = 100
py> id(a), id(b)
(18755392, 18925912)
py> a > b
True
py> b > a
False
So, even though b's id is higher than a's, b still compares as smaller
because the current CPython implementation special-cases the comparison
to guarantee that numbers are always smaller than all other non-None
objects.
Again, these are *all* implementation details of the current CPython,
and depending on these details might run you into troubles if they
change in a future version of CPython, or if you use a different
implementation (e.g. Jython or IronPython).
Steve
More information about the Python-list
mailing list