Can relational operators be applied to values other than numbers?


#1

Question

In the context of this exercise, can relational operators be applied to values other than numbers?

Answer

Yes, relational operators like >, <, >= and <= can be applied to values other than just numbers. They can also be applied to sequences of values like strings and lists. Strings are similar to a list of characters.

When comparing such values, the comparisons are done using ‘lexicographical’ (alphabetical) ordering. The first two items are compared, then the second two items, and so on. When any of the items are different, it will compare them based on their lexicographical ordering.

When comparing any two values, they must share the same type, or there will be a TypeError thrown.

Example

# This is False, "a" comes before "b" in lexicographical ordering.
"a" > "b"

# Lexicographical order follows alphabetical ordering.
# "a" < "b" < "c" …

# This is True because the first items match, and 1 < 3 for the second item.
[1, 2] < [1, 3]