Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to get len of nested list on python

my_list = [6,36,[54,5],13,[ 3,5], ["b",2]]
# do someting
...
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? I tried to use numpy but without success.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading