Reputation: 2732
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.
Upvotes: 15
Views: 9241
Reputation: 62373
values = [['a','a'], ['a','b','b'], ['a','b','b','a'], ['a','b','c','a']]
max(values, key=len)
[out]:
['a', 'b', 'b', 'a']
pandas
solution isn't a competitor with the accepted answer for speed in returning the first, longest list.pandas
for analysis, so this is a valid question, from that perspecive.df.len.max()
can be substituted with an int
, to return lists of a specified length.'len'
column is createdmax(df.lists, key=len)
can be used on a pandas.Series
to find the first, longest list.import pandas as pd
# convert the list of lists to a dataframe
df = pd.DataFrame({'lists': values})
# display(df)
lists
0 [a, a]
1 [a, b, b]
2 [a, b, b, a]
3 [a, b, c, a]
# create column for the length of each list
df['len'] = df.lists.map(len)
lists len
0 [a, a] 2
1 [a, b, b] 3
2 [a, b, b, a] 4
3 [a, b, c, a] 4
# select lists with max(len)
max_len = df[df.len == df.len.max()] # or [df.len == some int] for a specific length
# display(max_len)
lists len
2 [a, b, b, a] 4
3 [a, b, c, a] 4
%timeit
import pandas as pd
import random
import string
# 1M sub-list of 1-15 characters
l = [random.sample(string.ascii_letters, random.randint(1, 15)) for _ in range(10**6)]
%timeit max(l, key=len)
29.6 ms ± 1.74 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# function to do all the pandas stuff for testing
def get_max_len(l):
df = pd.DataFrame({'lists': l})
df['len'] = df.lists.map(len)
return df[df.len == df.len.max()]
%timeit get_max_len(l)
682 ms ± 14.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Upvotes: 2
Reputation: 6748
This will return the length of the longest list:
max(map(len, values))
Upvotes: 6
Reputation: 106445
This will return the longest list in the list values
:
max(values, key=len)
Upvotes: 37