how to find the longst element list of lists

Steven Bethard steven.bethard at gmail.com
Sun Jan 7 23:24:23 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):
>     maxlength, maxlist = max([(len(lst), lst) for lst in list_of_lists])

Generator expressions worked in 2.4 too. If you're using 2.5, you should 
take advantage of the key= argument to max and skip the generator 
expression entirely::

     >>> list_of_lists = [["q", "e", "d"],
     ...                  ["a", "b"],
     ...                  ["a", "b", "c", "d"]]
     >>> maxlist = max(list_of_lists, key=len)
     >>> maxlist, len(maxlist)
     (['a', 'b', 'c', 'd'], 4)

STeVe



More information about the Python-list mailing list