6

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
  • 10,118
  • 5
  • 41
  • 48
Rakesh K
  • 144
  • 1
  • 8

5 Answers5

13

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
  • 36,219
  • 6
  • 36
  • 71
4

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

>>> max(map(len, lst))
4
Sunitha
  • 11,422
  • 2
  • 17
  • 22
2

you can do it like the following:

max([len(item) for item in A])
OmG
  • 17,400
  • 7
  • 51
  • 81
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']]
>>> 
U12-Forward
  • 65,118
  • 12
  • 70
  • 89
-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
  • 10,118
  • 5
  • 41
  • 48