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 :
I would sum the flattened list:
def flatten(L): '''Flattens nested lists or tuples with non-string items''' for item in L: try: for i in flatten(item): yield i except TypeError: yield item >>> sum(flatten([1,3,5,6,[7,8]])) 30