Python inequality operators; comparing lists

4.4k views Asked by At

Having trouble understanding Python behavior when using inequality operators to compare lists. Here's a snippet using the python3 command line interpreter:

>>> [8] < [7]
False
>>> [8] < [9]
True
>>> [8, 6] < [9]
True
>>> [8, 6] < [9, 7]     
True                    # So far so good
>>> [8, 6] < [9, 5]     
True                    # Huh?

So, clearly Python isn't just moving through parallel indexes. I did find some information which says that in this scenario, Python orders the lists "lexicographically", which I guess means alphabetically.

So, I thought maybe the lists get sorted and then compared by parallel, but this is disproven by the following example:

>>> [1, 2, 3] < [3, 2, 1]
True

My guess was that the internal comparison would be [1, 2, 3] < [1, 2, 3], which should have returned False, since 1 < 1 is False, 2 < 2 is False, etc..

Any help is appreciated.

3

There are 3 answers

0
wvdz On BEST ANSWER

It actually makes a lot of sense.

The comparison is done similar as you would sort words, in lexicographical order. After all, words are also lists: lists of characters.

You first consider the first item. If one is smaller, the whole sequence is smaller, if they are equal, you move to the second item, etc.

Clearly, "86" comes before "95", just as "az" comes before "bc" and "100" comes before "90".

More here.

0
Steve Jessop On

clearly Python isn't just moving through parallel indexes

Yes it is, and it stops the first time it finds values that don't compare equal. This is indeed lexicographical order. Replacing the numbers in your examples with letters, and the lists with strings:

"h" < "g" # False
"h" < "i" # True
"hf" < "i" # True
"hf" < "ig" # True
"hf" < "ie" # True - not huh, hf does come before ie alphabetically.
"abc" < "cba" # True
1
Juergen On

What Python does is, just go over the lists in parallel and compare the elements of the same index. The first time it encounters elements that are not equal, it returns this result.

It is the same, as comparing words:

"Peter" > "Peer"

The first two letters are the same, the third is different and is giving the result. This is (for lists) the same technique used in a paper dictionary, just with list elements instead of characters.

Additional info: (as suggested by Padraic Cunningham): When one list is shorter and all elements up to the size of the shorter list where the same, the longer list is considered greater. This is also the same as in normal (paper) dictionaries.