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.
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
list of lists[[[1,2]]] to be 1 (the number of elements in the list-of-lists: this one element happens to be a list) or 2 (the number of elements at any level of nested lists).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.
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).
len with something like def mylen(iterable): try: return len(iterable) except TypeError: return sum(1 for x in iterable). That is, do it fast for iterables where that's possible, slow otherwise.
len(str(a).strip('[],').split(','))Edit I tried here: ideone.com/gzpt65