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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With