Home > Article > Backend Development > How does Python compare lists using the greater than or less than operator?
Comparing Lists with the Greater Than or Less Than Operator
When comparing two lists using the comparison operators (>, <), Python applies lexicographical ordering. This means that the lists are compared element by element, from left to right.
If at any point the leftmost elements of the lists are different, the outcome of the comparison is based on their values. However, if the corresponding elements are equal, the comparison moves on to the next pair of elements.
For instance:
a = [10, 3, 5] b = [5, 4, 3] print(a > b) # True (because the leftmost element 10 is greater than 5) print(b < a) # True (because the leftmost element 4 is less than 10)
Note that lexicographical ordering considers equal elements as "indifferent." Therefore, if two lists have the same elements in a different order, the comparison may still return True or False based on the order:
print([3, 3, 3, 3] > [4, 4, 4, 4]) # False print([4, 4, 4, 4] > [3, 3, 3, 3]) # True</p> <p>The outcome becomes less intuitive when the lists contain elements that differ in value:</p> <pre class="brush:php;toolbar:false">print([1, 1, 3, 1] > [1, 3, 1, 1]) # False print([1, 3, 1, 1] > [1, 1, 3, 3]) # True
These results are caused by the lexicographical ordering. When the leftmost elements are equal, Python moves on to the next pair. In the first example, the first two elements (1 and 1) are equal, so it compares the second pair (3 and 3). Since 3 is greater than 3, the first list is considered greater.
In the second example, when the leftmost elements are equal (1 and 1), the second pair is also equal (3 and 3). Thus, Python moves on to the next pair (1 and 1). Since 1 is equal to 1, the first list is still considered greater.
The above is the detailed content of How does Python compare lists using the greater than or less than operator?. For more information, please follow other related articles on the PHP Chinese website!