Search code examples
pythonlistcountitems

length of list contents with lists inside


Is there command to get total count of list items with lists inside?

Example:

Names = [['Mark'], ['John', 'Mary'], ['Cindy', 'Tom'], ['Ben']]
print (len(Names))

Output

4

But I want total count of list items so that result would be 6. I just started learning python, so go easy on me.


Solution

  • You can use map to apply a function to every element of an iterable. Here we apply the len function and sum the results:

    Names = [['Mark'], ['John', 'Mary'], ['Cindy', 'Tom'], ['Ben']]
    print(sum(map(len, Names)))
    # 6
    

    This (and all the other answers) works only as long as each element of Names is actually a list. If one of them is a str, it will add the length of the string and if it does not have a length (like int or float) it will raise a TypeError.

    Since the functional approach is sometimes frowned upon in modern Python, you can also use a list comprehension (actually a generator comprehension):

    print(sum(len(x) for x in Names))
    # 6