Skip to content Skip to sidebar Skip to footer

Why Does {}|[]|()|str|set|etc. > N Equals True In Python2.x?

I noticed this when trying to compare: if len(sys.argv) >= 2: pass but I had done this and still was True (Took me some time to find the bug.): if sys.argv >= 2: # This

Solution 1:

You are comparing different types. In Python 2, types are ordered relative to one another by their name, and numeric types are always ordered before everything else.

This was introduced to allow sorting of heterogeneous lists, containing different types of data.

Python 3 rectifies this somewhat surprising behaviour, there comparing types (to numbers or to one another) is always an error unless specifically allowed by custom comparison hooks:

>>> {} > 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: dict() > int()
>>> class Foo:
...     def __gt__(self, other):
...         if isinstance(other, int):
...             return True
... 
>>> Foo() > 3
True

Post a Comment for "Why Does {}|[]|()|str|set|etc. > N Equals True In Python2.x?"