-7

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.

kfnwtfn
  • 1
  • 2

2 Answers2

1

You could use a generator comprehension and the sum function.

l = [[0,1,2],[3,4,5]]
print(sum(len(x) for x in l))

Maybe you could chain it even at a map function:

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:

Alternate constructor for chain(). Gets chained inputs from a single iterable argument that is evaluated lazily. Roughly equivalent to:

def from_iterable(iterables):
    # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
    for it in iterables:
        for element in it:
            yield element

This flattens a list of lists, making some iterable like [[0,1,2],[3,4,5]] into something like [0,1,2,3,4,5], the lenght of the list above is the sum of the lenghts of the lists from the iterable above.

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)))
>>> 6
XxJames07-
  • 1,833
  • 1
  • 4
  • 17
0

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
Ash Nazg
  • 514
  • 3
  • 6
  • 14