Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the total number of elements in my arbitrarily nested list of lists?

I have a list assigned to the variable my_list. The value of my_list is [[1,2,3],[3,5,[2,3]], [[3,2],[5,[4]]]]. I need to find the length of my_list, but len(my_list) only returns 3. I want it to return 11. Is there any Python functions that will return the full length of my_list nested lists and all.

Example:

Input
[[1,2,3],[3,5,[2,3]], [[3,2],[5,[4]]]]

Output
11

I would like if this worked for not only numbers, but strings also.

like image 939
michaelpri Avatar asked Jan 04 '15 01:01

michaelpri


1 Answers

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.

like image 91
stonesam92 Avatar answered Oct 19 '22 03:10

stonesam92