Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Length of the longest sublist? [duplicate]

Tags:

python

list

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?

like image 380
IAmBatman Avatar asked Nov 15 '12 15:11

IAmBatman


People also ask

What is longest substring in Python?

Python Program To Find Length Of The Longest Substring Without Repeating Characters. Given a string str, find the length of the longest substring without repeating characters. For “ABDEFGABEF”, the longest substring are “BDEFGA” and “DEFGAB”, with length 6. For “BBBB” the longest substring is “B”, with length 1.

How do I find the longest item in a list Python?

Use Python's built-in max() function with a key argument to find the longest string in a list. Call max(lst, key=len) to return the longest string in lst using the built-in len() function to associate the weight of each string—the longest string will be the maximum.


1 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.

like image 55
mgilson Avatar answered Sep 18 '22 14:09

mgilson