Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two lists using the greater than or less than operator

Tags:

python

list

I noticed a piece of code recently directly comparing two lists of integers like so:

a = [10,3,5, ...] b = [5,4,3, ...,] if a > b:      ... 

which seemed a bit peculiar, but I imagined it would return True if all of list_a's elements are larger then list_b's and False if each element is equal or list_b's elements are larger then list_a's. So I tested it:

>>> a=[3,3,3,3] >>> b=[4,4,4,4] >>> a>b False >>> b>a True 

Ok that works. As does:

>>> b = [1,1,1,1] >>> a = [1,1,1,1] >>> a>b False >>> b>a False 

but when it gets more fuzzy:

>>> a=[1,1,3,1] >>> b=[1,3,1,1] >>> a>b False >>> b>a True 

or:

>>> a=[1,3,1,1] >>> b=[1,1,3,3] >>> a>b True >>> b>a False 

the results are a bit stranger. What is python actually doing? It seems that it's returning the result in favour of the first list in which the left most element is greater then the corresponding?

like image 753
Timmy O'Mahony Avatar asked Oct 24 '12 15:10

Timmy O'Mahony


People also ask

Is it possible to compare two lists using comparison operators explain?

Using list. sort() method sorts the two lists and the == operator compares the two lists item by item which means they have equal data items at equal positions. This checks if the list contains equal data item values but it does not take into account the order of elements in the list.

Can you compare lists with ==?

We can club the Python sort() method with the == operator to compare two lists. Python sort() method is used to sort the input lists with a purpose that if the two input lists are equal, then the elements would reside at the same index positions.


1 Answers

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.

like image 132
gefei Avatar answered Sep 27 '22 01:09

gefei