Comparing lists

Peter Otten __peter__ at web.de
Mon Aug 16 07:22:28 EDT 2010


Francesco Bochicchio wrote:

> Hi all,
> 
> anybody can point me to a description of how the default comparison of
> list objects (or other iterables) works?
> 
> Apparently l1 <  l2 is equivalent to  all ( x < y  for  x,y in
> zip( l1, l2) ), has is shown in the following tests, but I can't find
> it described anywhere:
> 
>>>> [1,2,3] < [1,3,2]
> True
>>>> [1,2,3] < [1,2,4]
> True
>>>> [1,2,3] < [2,2,3]
> True
>>>> [1,2,3] < [0,1,3]
> False
>>>> [1,2,3] < [0,2,3]
> False
>>>> [1,2,3] < [1,1,3]
> False
>>>> [1,2,3] < [1,2,2]
> False
> 
> 
> Ciao
> ---
> FB

Quoting http://docs.python.org/reference/expressions.html

"""
Tuples and lists are compared lexicographically using comparison of 
corresponding elements. This means that to compare equal, each element must 
compare equal and the two sequences must be of the same type and have the 
same length.
If not equal, the sequences are ordered the same as their first differing 
elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). 
If the corresponding element does not exist, the shorter sequence is ordered 
first (for example, [1,2] < [1,2,3]).
"""



More information about the Python-list mailing list