Length of the longest sublist?

Question:

Possible Duplicate:
Python’s most efficient way to choose longest string in list?

I have a list L

L = [[1,2,3],[5,7],[1,3],[77]]

I want to return the length of the longest sublist without needing to loop through them, in this case 3 because [1,2,3] is length 3 and it is the longest of the four sublists. I tried len(max(L)) but this doesn’t do what I want. Any way to do this or is a loop my only way?

Asked By: IAmBatman

||

Answers:

max(L,key=len) will give you the object with the longest length ([1,2,3] in your example) — To actually get the length (if that’s all you care about), you can do len(max(L,key=len)) which is a bit ugly — I’d break it up onto 2 lines. Or you can use the version supplied by ecatamur.

All of these answers have loops — in my case, the loops are implicit which usually means they’ll be executed in optimized native machine code. If you think about it, How could you know which element is the longest without looking at each one?


Finally, note that key=function isn’t a feature that is specific to max. A lot of the python builtins (max,min,sorted,itertools.groupby,…) use this particular keyword argument. It’s definitely worth investing a little time to understand how it works and what it typically does.

Answered By: mgilson

Try a comprehension:

max(len(l) for l in L)
Answered By: ecatmur
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.