Index of array with maximum length

Viewed 297

I am trying to get the index of the array with the longest length. I have this array of arrays.

[
 [0,7,3],
 [1],
 [2,6,5,2,9],
 [1,2]
]

The desired outcome is 2 because it is the array with the maximum length. I have this working code:

max_len = -1
index = -1

for i, feature in enumerate(features):
    if max_len < len(feature):
        max_len = len(feature)
        index = I

print(index)

I think that should be a one-liner or a much better and simpler way to do it. Does anyone know a better way to do it?

Thanks!

3 Answers

That looks like a python list, not a numpy array. You can use l.index(max(l, key=len)) if l is your list.

You can use enumerate and max for this one:

max_length_index, _ = max(enumerate(l), key=lambda index_and_lst  : len(index_and_lst[1]))

This is a one-liner:

vals = [[0,7,3],[1],[2,6,5,2,9],[1,2]]
pd.Series(vals).apply(lambda x: len(x)).idxmax()

You could also do this without pandas:

lens = [len(val) for val in vals]
print(lens.index(max(lens)))
Related