how to find the longst element list of lists

Scott David Daniels scott.daniels at acm.org
Mon Jan 8 04:50:16 CET 2007


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])

--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list