Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python how to find max length of inner list in a 2D list? [duplicate]

Tags:

python

numpy

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.

like image 302
Rakesh K Avatar asked Dec 10 '22 05:12

Rakesh K


2 Answers

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

like image 126
Netwave Avatar answered Mar 15 '23 23:03

Netwave


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

>>> max(map(len, lst))
4
like image 25
Sunitha Avatar answered Mar 16 '23 00:03

Sunitha