How do I count the number of elements in a nested list?
I want to transform:
myList = [[0],[1,4,5,8],[5],[2,3,9],[7,7]]
into:
myList = [1, 4, 1, 3, 2]
Python gives you the map
function which allows you to apply a function to each element in a list. You could simply write:
result = list(map(len, myList))
Use a list comprehension:
>>> [len(l) for l in myList]
[1, 4, 1, 3, 2]
Another way is to use map
:
>>> list(map(len, myList))
[1, 4, 1, 3, 2]
For a two dimension list like you have shown you can use the following code
res = [len(x) for x in myList]
or you could use a map function as follows
res = list(map(len, myList))