Comparing Lists with the Greater Than or Less Than Operator: Lexicographical Ordering Unsurprises
Upon encountering code comparing lists directly using the greater than or less than operator (> and <), you might assume that such comparisons return True if all elements in the first list are greater than those in the second list, and False otherwise. However, testing reveals unexpected results.
To unravel this mystery, we turn to Python's documentation on Comparing Sequences and Other Types. It states that such comparisons follow lexicographical ordering, not element-by-element comparisons:
Consider the following example:
a = [3, 3, 3, 3] b = [4, 4, 4, 4]
Since the first elements (3 and 4) differ, b is considered greater than a. This aligns with our assumption that all elements in b are greater than those in a.
However, the following case illustrates the lexicographical ordering rule more clearly:
a = [1, 1, 3, 1] b = [1, 3, 1, 1]
Since the first elements (1) are equal, the comparison moves on to the next elements. In this case, the second element of a (1) is less than the second element of b (3). Therefore, despite the fact that a has more elements greater than 1 than b does, b is considered greater than a.
In summary, when comparing lists using the greater than or less than operator, Python employs lexicographical ordering, rather than element-by-element comparisons. This can lead to unexpected results, especially when lists contain elements of different values.
The above is the detailed content of How Does Python Compare Lists with Greater Than and Less Than Operators?. For more information, please follow other related articles on the PHP Chinese website!