Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a max string length in nested lists

Tags:

python

They is a follow up question to my earlier post (re printing table from a list of lists)

I'm trying t get a string max value of the following nested list:

tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

for i in tableData:
    print(len(max(i))) 

which gives me 7, 5, 5. But "cherries" is 8

what a my missing here? Thanks.

like image 856
AT_1965 Avatar asked Mar 11 '23 04:03

AT_1965


1 Answers

You've done the length of the maximum word. This gives the wrong answer because words are ordered lexicographically:

>>> 'oranges' > 'cherries'
True

What you probably wanted is the maximum of the lengths of words:

max(len(word) for word in i)

Or equivalently:

len(max(i, key=len))
like image 142
wim Avatar answered Mar 21 '23 09:03

wim