33

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?

Georgy
  • 12,464
  • 7
  • 65
  • 73
IAmBatman
  • 687
  • 1
  • 10
  • 20

2 Answers2

62

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.

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • How does that work? Ah ok so there's no way to avoid it? Alright -- thanks! – IAmBatman Nov 15 '12 at 15:38
  • @IAmBatman Did you read the documentation of `max`? Are you aware that functions are first class-values (which means, among other things, that they can be passed to other functions as arguments)? –  Nov 15 '12 at 15:39
  • @IAmBatman -- `max` applies the `key` function to each element of your list and picks the one where the `key` function returned the biggest. – mgilson Nov 15 '12 at 15:39
  • @delnan I know that functions can be used as arguments, yes... I just don't have much experience using them in that way is all – IAmBatman Nov 15 '12 at 15:40
  • @IAmBatman: Indeed you have to, if you wanted to know the largest length. – Martijn Pieters Nov 15 '12 at 15:42
19

Try a comprehension:

max(len(l) for l in L)
ecatmur
  • 152,476
  • 27
  • 293
  • 366
  • 1
    Using the `key` keyword is faster, I think. – Martijn Pieters Nov 15 '12 at 15:40
  • @MartijnPieters Likely, seeing as it's in C (and PyPy has troubles optimizing generator expressions in some cases). But that's not why I'd recommend it. It's also clearer to me (but this is fine too, and I have noticed I lean more towards functional programming than many Python programmers). –  Nov 15 '12 at 15:41
  • 2
    @MartijnPieters -- There are very subtle differences. `max(L,key=len)` gives the object with the biggest `len`, but it doesn't give you it's length :) – mgilson Nov 15 '12 at 15:41
  • @mgilson: I just realized this as well. :-) – Martijn Pieters Nov 15 '12 at 15:42