0
def nested_sum(L):
    return sum( nested_sum(x) if isinstance(x, list) else x for x in L )

This was a solution given by Eugenie in the following post: sum of nested list in Python

I just was trying to recreate it without using comprehension list, but I'm not able to get it. How could I do it?

Community
  • 1
  • 1
ezitoc
  • 729
  • 1
  • 6
  • 9

1 Answers1

0

The code uses a generator expression, not a list comprehension.

Use a loop and += adding up the results:

def nested_sum(L):
    total = 0
    for x in L:
        total += nested_sum(x) if isinstance(x, list) else x
    return total

or, if you want the conditional expression expanded into an if statement as well:

def nested_sum(L):
    total = 0
    for x in L:
        if isinstance(x, list):
            total += nested_sum(x)
        else:
            total += x
    return total
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343