Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the longest list in a list?

Given a list of lists, the length of the longest list can be found with the following code.

values = [['a','a'], ['a','b','b'], ['a','b','b','a'], ['a','b','c','a']]

longest = 0
for value in values:
    longest = max(longest, len(value))

print(longest)
[out]: 4

How can the length of the longest list, or the longest list be found, without a loop.

like image 357
Cody Smith Avatar asked Aug 26 '18 01:08

Cody Smith


2 Answers

This will return the longest list in the list values:

max(values, key=len)
like image 74
blhsing Avatar answered Oct 13 '22 00:10

blhsing


This will return the length of the longest list:

max(map(len, values))
like image 35
whackamadoodle3000 Avatar answered Oct 12 '22 22:10

whackamadoodle3000