How can I get the total number of elements in my arbitrarily nested list of lists?
This function counts the length of a list, counting any object other than list as length 1, and recursing on list items to find the flattened length, and will work with any degree of nesting up to the interpreters maximum stack depth.
def recursive_len(item):
if type(item) == list:
return sum(recursive_len(subitem) for subitem in item)
else:
return 1
Note: depending on how this will be used, it may be better to check if the item is iterable rather than checking if it has the type list
, in order to correctly judge the size of tuples, etc. However, checking if the object is iterable will have the side effect of counting each character in a string rather than giving the string length 1, which may be undesirable.
As an alternative, you can use flatten with len:
from compiler.ast import flatten
my_list = [[1,2,3],[3,5,[2,3]], [[3,2],[5,[4]]]]
len(flatten(my_list))
11
PS. thanks for @thefourtheye pointing out, please note:
Deprecated since version 2.6: The compiler package has been removed in Python 3.
Alternatives can be found here: Python 3 replacement for deprecated compiler.ast flatten function
hack solution, someone had to post it. Convert list to string (leave the heavy lifting / recursion to __str__
operator) then count the commas, add 1.
>>> my_list = [[1,2,3],[3,5,[2,3]], [[3,2],[5,[4]]]]
>>> str(my_list).count(",")+1
11
(works for integers & floats, of course fails with strings because they can contain commas)
EDIT: this hack doesn't account for empty lists: we have to remove []
elements:
>>> my_list = [[1,2,3],[3,5,[2,3]], [[3,2],[5,[4],[]]]] # added empty list at the end
>>> s = str(my_list)
>>> s.count(",")-s.count("[]")+1 # still 11