-3

Python 3 does not support comparison between different data types.
1 < '1' will execute with:

`TypeError: '<' not supported between instances of 'float' and 'str'`

But why does 1 == '1' (or something like 156 == ['foo']) returns False?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Elantonio
  • 1
  • 1
  • Equality of different tyes will always yield `False`. Because the objects are of different types, they obviously can't be equal. But how can you compare different types? What would be the result of `156 < "foo"`? – Tomerikoo Sep 27 '20 at 12:57
  • 1
    Does this answer your question? [In Python, how to know whether objects can be compared?](https://stackoverflow.com/questions/29457135/in-python-how-to-know-whether-objects-can-be-compared) OR https://stackoverflow.com/questions/55694996/what-are-built-in-python-3-types-that-can-be-compared-to-each-other – Tomerikoo Sep 27 '20 at 13:08

2 Answers2

1

from the docs:

The default behavior for equality comparison (== and !=) is based on the identity of the objects. Hence, equality comparison of instances with the same identity results in equality, and equality comparison of instances with different identities results in inequality. A motivation for this default behavior is the desire that all objects should be reflexive (i.e. x is y implies x == y).

Sometimes we would like to know if two variable are the same, meaning that they refer to the same object, e.g. True is True will return True, but on the other hand "True" is True returns False, hence it makes sense that "True" == True returns False (I didn't provide the best use case for using is operator and this example will raise a SyntaxWarning in Python3.8+ but that's the main idea)

Waad
  • 385
  • 1
  • 8
0

Because it makes sense to check if something is equal to something else (or is it something else) even if they are not of the same type. However, it doesn't make much sense to check which "quantity" is larger if they aren't of the same type because "quantity" may be defined in a different way for each type (in other words, the "quantity" might measure a different quality of the object).

A non-code example: an apple clearly can not be == to an orange. However, if we define the "quantity" of an apple to be its "redness", and the "quantity" of an orange to be its "taste", we can not check if an apple is > than an orange. > will try to compare different qualities of these objects.

Back to code: It is clear that 4 is not (or is not equal to) the list [4]. But what meaning will a check like 4 > [4] have? what does it mean for an integer to be "smaller" or "larger" from a list?

DeepSpace
  • 78,697
  • 11
  • 109
  • 154