Bob
Bob

Reputation: 55

Python sum in list consists of integers and other lists and nested lists

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

Upvotes: 1

Views: 228

Answers (3)

Adrien
Adrien

Reputation: 433

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)

Upvotes: 1

Onyambu
Onyambu

Reputation: 79288

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

Upvotes: 2

Andrej Kesely
Andrej Kesely

Reputation: 195543

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

Upvotes: 2

Related Questions