Home > Enterprise >  How to find the length of a list of list of string using python version 3?
How to find the length of a list of list of string using python version 3?

Time:07-27

input:

letters = [['a', 'b', 'c'], ['a', 'b', 'c']]

output:

6

I tried to do len(letters), but for obvious reason it doesn't work.

Then I tried to do a for loop:

for char in letters:
        for s in char:
           print(len(s))

but that doesn't work either.

CodePudding user response:

You could use a list comprehension here:

letters = [['a', 'b', 'c'], ['a', 'b', 'c']]
num = sum([len(x) for x in letters])
print(num)  # 6

CodePudding user response:

As you need count of all the letters in the inner lists, you just need to add the len count of each list.

letters = [['a', 'b', 'c'], ['a', 'b', 'c']]
l=0
for char in letters:
    l =len(char)
print(l)

Output:

6

CodePudding user response:

You could use a generator comprehension and the sum function.

Maybe you could chain it even at a map function.

Here is sample code to test this:

l = [[0,1,2],[3,4,5],[4,5,6]]
print(sum(map(len,l)))
>>> 9

This could also be done by using the itertools.chain.from_iterable function:

here is some code to test what said above:

import itertools
l = [[0,1,2],[3,4,5]]
print(len(itertools.chain.from_iterable(l)))
  • Related