a = [[1,2,3],[4,1],[2,2,6],[3]]
the sum of a would print 24
I know for a single list such as [1,2,3] i can just do sum(a) but I'm struggling with a nested list.
Thank you.
This does not create a new temporary list:
sum(sum(b) for b in a)
sum(itertools.chain(*a)). However, I'm not sure why someone would simply rule out itertools.b is one of your sublists. To see how this works use a for-loop: for b in a:print b.sum(sum(a, []))
The inner sum combines all the individual lists into one list. The outer sum then finds the actual sum.
For lists that are nested more than one deep, you can use this:
def recursiveSum(data):
try:
total = 0
for item in data:
total += recursiveSum(item)
return total
except TypeError: #data isn't iterable, it's probably a number
return data
print recursiveSum([[[[1,2,3],[4,1]],[2,2,6]],3])
output:
24