9

I often create a list of lists with varying length of inner list, for e.g. to represent a bunch of sentences of varying length

[['Hello', 'world'], ['how','are','you'], ['have','a','good','day']]

I need these to be converted to numpy matrix. To make all inner lists of same length I pad a dummy element at the end and make all inner lists equal the maximum length.

Is there any compact way of finding the max length of inner list?

I usually do it by writing a for loop and keeping track of the max length but I do it so often that I feel the need for a better way.

Guillaume Jacquenot
  • 11,217
  • 6
  • 43
  • 49
Rakesh K
  • 173
  • 1
  • 10

5 Answers5

15

Using max function:

max(your_list, key=len)

You will get the longest list, if you need the actual length just use len again:

len(max(your_list, key=len))

Here you have the live example

Netwave
  • 40,134
  • 6
  • 50
  • 93
4

Using map and max, you find the max length of the sub lists easily

>>> max(map(len, lst))
4
Sunitha
  • 11,777
  • 2
  • 20
  • 23
2

you can do it like the following:

max([len(item) for item in A])
OmG
  • 18,337
  • 10
  • 57
  • 90
2

And order it:

>>> A=[['Hello', 'world'], ['how','are','you'], ['have','a','good','day']]
>>> sorted(A,key=len)
[['Hello', 'world'], ['how', 'are', 'you'], ['have', 'a', 'good', 'day']]
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
-1

To convert your list of lists in a numpy array, you can try the following snippet. The fourth line pads your data and the fifth line creates the numpy array.

import numpy as np
data=[['Hello', 'world'], ['how','are','you'], ['have','a','good','day']]
max_length = max(map(len, data))
[e1.extend(['']*(max_length - len(e1))) for e1 in data]
np_data=np.array(data)
Guillaume Jacquenot
  • 11,217
  • 6
  • 43
  • 49