How to get length of nested list in Python

Issue

my_list = [6, 36, [54, 5], 13, [3, 5], ["b", 2]]
# do something
...
print(len(new_list))
>>> 9

I have a nested list in Python. How should I go about reaching the number of elements of this list?

Solution

Assuming a classical python list, this can typically be solved by recursion:

my_list = [6,36,[54,5],13,[ 3,5], ["b",2]]

def nelem(l, n=0):
    if isinstance(l, list):
        return sum(nelem(e) for e in l)
    else:
        return 1
    
nelem(my_list)
# 9

collecting the elements:

my_list = [6,36,[54,5],13,[ 3,5], ["b",2]]

def nelem(l, n=0, out=None):
    if isinstance(l, list):
        return sum(nelem(e, out=out) for e in l)
    else:
        if out is not None:
            out.append(l)
        return 1
    
x = []
n = nelem(my_list, out=x)
print(n)
# 9

print(x)
# [6, 36, 54, 5, 13, 3, 5, 'b', 2]

Answered By – mozway

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published