1

I have problem with a function that returns a sum of values in list given as argument. But this list can consists of integers and other lists, but this lists can have other lists etc etc like in example: [10, 5, [1, [5, 4, 3]], 9, [1, 1, [2, 3]]] => 44

Bob
  • 55
  • 3
  • Does this answer your question? [sum of nested list in Python](https://stackoverflow.com/questions/14917092/sum-of-nested-list-in-python) – A.M. Ducu Jun 28 '21 at 22:30

3 Answers3

2

You can flatten the list and then sum it:

lst = [10, 5, [1, [5, 4, 3]], 9, [1, 1, [2, 3]]]


def flatten(l):
    if isinstance(l, list):
        for v in l:
            yield from flatten(v)
    else:
        yield l


out = sum(flatten(lst))
print(out)

Prints:

44
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
2

You could also write a recursive function that does the summation:

def my_sum(x):
    value = 0
    for i in x:
        if not isinstance(i, list):
           value += i
        else:
           value += my_sum(i)
    return value

my_sum(lst)
44
Onyambu
  • 67,392
  • 3
  • 24
  • 53
1

Using a recursive function should work :

def your_function(embeded_list):
    n = len(embeded_list)
    sum = 0
    for i in range(n) :
       if len(embeded_list[i]) == 1 :
           sum+=embeded_list[i]
       else :
           sum+=your_function(embeded_list[i])
    return(sum)
Adrien
  • 433
  • 1
  • 3
  • 13
  • please do not use len + range, iterate on iterables and test using isinstance is much cleaner and readable – DevLounge Jun 28 '21 at 22:47