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
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to