1
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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
daniel
  • 25
  • 4
  • Does this answer your question? [How can I get the total number of elements in my arbitrarily nested list of lists?](https://stackoverflow.com/questions/27761463/how-can-i-get-the-total-number-of-elements-in-my-arbitrarily-nested-list-of-list) – mkrieger1 Jun 29 '22 at 15:02

3 Answers3

3

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]
mozway
  • 194,879
  • 13
  • 39
  • 75
  • Thank you for the answer. so can i collect all the elements in one list? [6,36,54,5,13, 3,5, "b",2] – daniel Jun 29 '22 at 09:18
  • There are many ways, a simple one would be to pass a list that will be mutated by the function, see update. – mozway Jun 29 '22 at 09:22
0

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
paime
  • 2,901
  • 1
  • 6
  • 17
-1

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

Zain Ul Abidin
  • 2,467
  • 1
  • 17
  • 29