Reputation: 289
Hello I am trying to count all the elements in a list of lists. For example
a = [[1,2],[3,4],[10,3,8]]
I want to return:
7
I tried count and size with no luck. Thanks in advance.
Upvotes: 1
Views: 2921
Reputation: 2089
You can flatten that list and then use len()
on the flattened list:
a = [[1,2],[3,4],[10,3,8]]
flattened_a = [item for sublist in a for item in sublist]
len(flattened_a)
Upvotes: 0
Reputation: 2047
list_count = 0
mainList = [[1,2],[3,4],[10,3,8]]
for inner_list in mainList:
list_count += len(inner_list)
print(list_count)
Upvotes: 0
Reputation: 239443
a = [[1,2],[3,4],[10,3,8]]
print(sum(map(len, a)))
Output
7
This can be written as a generator expression, like this
print(sum(len(item) for item in a))
The simplest method which would work even for multilevel nested lists, goes like this
def get_size(current_item):
if isinstance(current_item, list):
return sum(get_size(item) for item in current_item)
else:
return 1
a = [[1,2],[3,4],[10,3,8],[[1, 2, 3], [2, 3]]]
print get_size(a) # 12
Upvotes: 8
Reputation: 113915
def myLen(L):
if not L:
return 0
elif not isinstance(L[0], list):
return 1 + myLen(L[1:])
else:
return myLen(L[0]) + myLen(L[1:])
Output:
>>> myLen([[1,2],[3,4],[10,3,8]])
7
Upvotes: 0
Reputation: 54163
For academic purposes, if your list is more than one level deep (e.g. [ [1,2,3], [4,5,[6,7,8]]]
, one of your elements contains a list) you'll want to do something like:
def count_elements(target):
count = 0
for element in target:
if type(element) is list:
count += count_elements(element)
else:
count += 1
return count
But the problem as described by OP is easier-solved with one of the other answers. Just mentioning that those solutions are not easily scalable.
Upvotes: 1
Reputation: 64298
You can either sum the lengths (like @thefourtheye suggested), or iterate over all elements, and count:
sum(len(b) for b in a)
sum(1 for b in a for c in b)
The first way is clearly better, but the second is nice for demonstrating some things you can do with list comprehensions, and would also work on a more general structure, of iterable of iterables (which do not have __len__
defined).
Upvotes: 0