0

In Python, print(1 == '1') returns False but print(1 > '1') raises a TypeError. Why?

0

2 Answers 2

3

Equality always has a sensible definition

Conceptually, == checks if two objects are the same. This notion is perfectly well-defined for objects of different types.

  • Is the number 1 the same thing as the word "gold"? Clearly not.
  • Is my cat the same thing as the empty set? Clearly not.

The answers to these questions are not "I don't know" but "no". So the operator == should return False, not raise an exception, on objects of different types.

Ordering does not always have a sensible definition

Now consider >. Conceptually, this checks if one object is "greater than", or "after", another. But there are clearly some pairs of types for which this isn't well-defined.

  • Is 2+3i greater than, or after, 3+2i?
  • Is my cat greater than, or after, your cat?
  • Is the number one greater than, or after, the word "gold"?

None of these questions have sensible answers. So > doesn't have a sensible definition on imaginary numbers, or cats, or between numbers and strings, and should raise an exception.

A note on coercion

We might think 1 > "1" has a natural definition by converting ("coercing") "1" to an integer. But combined with the order on strings (which does have a definition: "gold" is before "silver" in the dictionary), this leads to losing transitivity: 3 is greater than 2 and "2" is alphabetically after "12", but 3 is not greater than 12.

Sign up to request clarification or add additional context in comments.

Comments

1

I was looking into the document, it says:

The <, <=, > and >= operators are only defined where they make sense; for example, they raise a TypeError exception when one of the arguments is a complex number.

So, if you do:

1 > '1'

you will get a TypeError

TypeError: '>' not supported between instances of 'int' and 'str'

It is something like :

1 > 'a'

You are comparing an integer to string.



Coming back to

1 == '1'

The == operator is always defined but for some object types (for example, class objects) is equivalent to is.

Link to document: https://docs.python.org/3/library/stdtypes.html#comparisons

I think By the nature of == it will always gives a Boolean (True/False) value.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.