Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list greater than number [duplicate]

Tags:

I have discovered that a list is greater than a number.

>>> [1,2,3] > 1000
True

Is there some reason why this works? I can't convert a list to an int with int([1,2,3]). The int can't be converted to a list with list(1000). So how is python comparing the two?

like image 937
Keyo Avatar asked Aug 23 '11 21:08

Keyo


2 Answers

In this case of "mismatched" types, the types are listed lexicographically by type name: a "list" comes after an "int" in alphabetical ordering, so it is greater.

CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address. (source)

There is no language specification for the ordering (apart from the fact that it is consistent). It just happens to be the case that CPython is the most common implementation in which there is this language detail of being ordered lexicographically by type names.

like image 100
Uku Loskit Avatar answered Oct 18 '22 14:10

Uku Loskit


According to the Python Reference Manual,

Most other objects of built-in types compare unequal unless they are the same object; the choice whether one object is considered smaller or larger than another one is made arbitrarily but consistently within one execution of a program.

like image 35
rmmh Avatar answered Oct 18 '22 14:10

rmmh