Search code examples
pythonstrong-typingtypingdynamic-typing

Why can a list be compared with an integer in Python


I have searched and no one seems to have this specific question. Why does Python let me compare a list with an integer? For instance,

[] < 10

evaluates to False

and

[] > 10

evaluates to True

Aren't these operations ill-defined and shouldn't Python throw an exception for these operations?


Solution

  • As of Python 3.x, you are correct this is no longer allowed

    >>> [] < 10
    Traceback (most recent call last):
      File "<pyshell#0>", line 1, in <module>
        [] < 10
    TypeError: unorderable types: list() < int()
    

    As for why this worked in Python 2.x, read here