Reputation: 3057
import math
lists = [1,[2,3],4]
total = 0
for i in range(len(lists)):
total += sum(i)
print(total)
I want it to print,
>>>10
But throws an error.
I would like it to get it to add all numbers, including the ones within the nested if.
Upvotes: 4
Views: 4284
Reputation: 411
numpy.hstack() function is used to stack the sequence of input arrays horizontally (i.e. column wise) to make a single array which is what we require in OP example
import numpy as np
list1 = [1,[2,3],4]
M = np.hstack(list1)
print(np.sum(M))
gives
10
[Program finished]
Upvotes: 0
Reputation: 8726
You can use flatten function in the compiler.ast module to flatten the list. Then simply sum up all the elements.
>>> lists = [1,[2,3],4]
>>> from compiler.ast import flatten
>>> sum(flatten(lists))
10
EDIT: Only works with Python 2.x
Upvotes: 6
Reputation: 99660
In your program, for i in range(len(lists))
- evaluates to 3 as the lists
object has 3 element. and in the loop total += sum(i)
it would try to do a int
+ list
operation, which results in an error. Hence you need to check for the type and then add the individual elements.
def list_sum(L):
total = 0
for i in L:
if isinstance(i, list):
total += list_sum(i)
else:
total += i
return total
This is @pavelanossov 's comment - does the same thing, in a more elegant way
sum(sum(i) if isinstance(i, list) else i for i in L)
Upvotes: 7