0

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]
jjwright
  • 39
  • 4

4 Answers4

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))
1

With only 2 dimension:

[len(sub_list) for sub_list in myList]
Teddy
  • 19
  • 3
0

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]
Corralien
  • 109,409
  • 8
  • 28
  • 52
0

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))
Aamir Shah
  • 31
  • 7