Search code examples
pythonpython-3.xstring-length

How to get the length of the longest string in a nested list of strings?


Newbie to Python here. I am trying to find the longest length of a value within a series of nested lists. Here is an example list type:

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

The answer that I want here is 8, but this could change if the list is updated.

When I use print(len(tableData)) I get 3, the number of nested lists. I cannot get a loop working that solves this either.

Sorry for this being a really simple question, but I am at a loss.

Thanks in advance for the help.


Solution

  • As you note, len(tableData) gives the number of elements of tableData. What you want is the max of the lengths of the elements of the elements of tableData:

    l = max(len(x) for sublist in tableData for x in sublist)
    

    >>> print(l)
    8