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.
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
Using map
and max
, you find the max length of the sub lists easily
>>> max(map(len, lst))
4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With