how to find the longst element list of lists

Peter Otten __peter__ at web.de
Mon Jan 8 03:42:34 EST 2007


Scott David Daniels wrote:

> Dan Sommers wrote:
>> ...
>>     longest_list, longest_length = list_of_lists[ 0 ], len( longest_list
>>     ) for a_list in list_of_lists[ 1 : ]:
>>         a_length = len( a_list )
>>         if a_length > longest_length:
>>             longest_list, longest_length = a_list, a_length
>> will run faster than sorting the list just to pick off one element (O(n)
>> vs. O(n log n) for all of you Big-Oh notation fans out there; you know
>> who you are!).
> 
> Or, more succinctly, after:
>      list_of_lists = [["q", "e", "d"],
>                       ["a", "b"],
>                       ["a", "b", "c", "d"]]
> You can find the longest with:
>      maxlength, maxlist = max((len(lst), lst) for lst in list_of_lists)
> or (for those pre-2.5 people):

pre-2.4 

>      maxlength, maxlist = max([(len(lst), lst) for lst in list_of_lists])

With the caveat that if there are lists of equal length their items will be
compared:

>>> max((len(lst), lst) for lst in [[1], [1j]])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: no ordering relation is defined for complex numbers

So if you want the first out of the lists with equal length on a python
where Steve's enhancement is not yet available (pre-2.5):

>>> max_len, dummy, max_list = max((len(lst), -i, lst) for i, lst in
enumerate([[1], [1j]]))
>>> max_len, max_list
(1, [1])

Peter



More information about the Python-list mailing list