I try to sum a list of nested elements
e.g, numbers=[1,3,5,6,[7,8]] should produce sum=30
numbers=[1,3,5,6,[7,8]]
sum=30
I wrote the following code :
One alternative solution with list comprehension:
>>> sum( sum(x) if isinstance(x, list) else x for x in L ) 30
Edit: And for lists with more than two levels(thx @Volatility):
def nested_sum(L): return sum( nested_sum(x) if isinstance(x, list) else x for x in L )