Home > Software engineering >  How to get length of nested list in Python
How to get length of nested list in Python

Time:06-30

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?

CodePudding user response:

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]

CodePudding user response:

To make it more general, you need a way to flatten your sequence, regardless how nested it is.

Then just apply the len function:

def flattened(iterable):
    for obj in iterable:
        if is_iterable(obj):
            yield from flattened(obj)
        else:
            yield obj

def is_iterable(x):
    if isinstance(x, str):
        return False
    try:
        iter(x)
    except TypeError:
        return False
    return True

Usage:

>>> l = [6, 36, [54, 5, ["bar", "baz"], 13, [3, 5], ["foo", [1, 2, 3]]]]
>>> list(flattened(l))
[6, 36, 54, 5, 'bar', 'baz', 13, 3, 5, 'foo', 1, 2, 3]
>>> len(list(flattened(l)))
13

CodePudding user response:

use python built-in function len() accepting the variable of list with the inner child key defined in the brackets

  • Related