Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the largest/smallest object in a python generator/list

Tags:

python

Let's say I have a generator gen which yields some lists. I'd like to find the longest list.

I can do

max((len(L) for L in gen))

which will get me the length of the longest list, but at this point the list is gone to the mists of time.

Alternately I could do

maxlength = 0
for L in gen:
    if len(L)>maxlength:
        savelist = L
        maxlength = len(L)

But it seems there should be a more pythonic way that avoids the for loop and the if statement.

edit just a comment to help others who might search for related problems: Finding the smallest object with min can be done equivalently, and the same approach will work if gen is a list instead.

like image 493
Joel Avatar asked Oct 13 '15 11:10

Joel


1 Answers

max has a keyword-only argument key that will accept a function by which to judge which is largest.

result = max(gen, key=len)

This would be equivalent to something like:

result = [el for _, el in sorted([len(el), el for el in gen])][-1]
# note that `sorted` takes a `key` argument too!
# # result = sorted(gen, key=len)[-1]

But obviously MUCH easier to read

like image 160
Adam Smith Avatar answered Oct 16 '22 00:10

Adam Smith