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
?
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
?
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)
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?