1

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.

2
  • 1
    For multiple-levels deep len(str(a).strip('[],').split(',')) Edit I tried here: ideone.com/gzpt65 Commented Feb 6, 2014 at 18:06
  • for your list: ideone.com/U1f93P Commented Feb 6, 2014 at 18:12

6 Answers 6

8
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
Sign up to request clarification or add additional context in comments.

10 Comments

Note that this won't work if your lists are multiple-levels deep. In that case you'll need to use a recursive solution.
@adsmith Agreed, but OP says, just list of lists
In fact, since the questioner wants to count the elements in a list of lists, then recursing through any number of levels of list would give the wrong answer in the case where the lists are more levels deep. It's a question of whether you want the answer for [[[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).
@SteveJessop Yes but in my experience, people will often over-simplify their questions in order to create a short complete example, so I wanted to drop a note in case OP comes back and says "No that's giving me the wrong result" when he applies it to his 300-element list of lists with lists.
@thefourtheye Thank you for your update. I felt bad for having a correct answer that I essentially just "guessed," plus your recursion is much prettier than mine :)
|
1

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.

Comments

0

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

1 Comment

For the iterable of iterables you probably want to replace the use of 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.
0
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

Comments

0
list_count = 0

mainList = [[1,2],[3,4],[10,3,8]]
for inner_list in mainList:
  list_count += len(inner_list)

print(list_count)

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.