Comparing two lists using the greater than or less than operator
From Comparing Sequences and Other Types in the Python tutorial:
The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted.
See also the Wikipedia article about lexicographical order.
Since I didn't find the explanation of list/tuple comparison using "lexicographical ordering" particularly illuminating at first, here's an attempt to explain it "in my own words". First, here are some example lists that are referred to in the explanation below:
a = [1, 2, 3]
b = [1, 2, 10]
c = [1, 2, 3, 100]
d = [1, 2, 3]
e = [1, 2, 3, 4, 'a']
f = ['a', 'b', 'c']
The pair of items at each index are compared in turn. So, comparing a
to b
will result in 1
being compared to 1
, 2
being compared to 2
, and 3
being compared to 10
.
The comparison of pairs will stop when either an unequal pair of items is found or--if the lists are different lengths--the end of the shorter list is reached.
For example, when comparing a
and b
, comparisons will stop when 3
and 10
are compared. When comparing b
and c
, comparisons will stop when 10
and 3
are compared.
As soon as an unequal pair is found, the overall result is the result of comparing the unequal items. This applies whether the lists are the same length or not--for example, list b
is greater than list c
because the 100
in c
never comes into play.
For example, when comparing a
to b
, the overall result will be the result of comparing 3
to 10
. a < b -> True
because 3
is less than 10
. a > b -> False
because 3
is not greater than 10
. a == b -> False
because 3
does not equal 10
.
If one of the lists is shorter and its N items are equal to the first N items of the longer list, as with a
and c
, the shorter list will be considered less than the longer list (so a
is less than c
).
Two lists will compare as equal only if they're the same length and all pairs of items compare as equal.
Note about types: if the items in a pair aren't comparable, the comparison will fail with a TypeError
as usual. For example, comparing list a
to f
will fail when 1
is compared to 'a'
. But also note that lists d
and e
can be compared since the 'a'
in e
is never compared to anything in d
.