Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python inequality operators; comparing lists [duplicate]

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.

like image 349
StayCool Avatar asked Jun 21 '15 11:06

StayCool


1 Answers

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.

like image 174
Juergen Avatar answered Oct 14 '22 13:10

Juergen