For example,
a = ([1,2,3],[4,5,6],[7,8,9])
sum returned should = 45
Use sum in a nested fashion:
>>> a = ([1,2,3],[4,5,6],[7,8,9])
>>> sum(sum(x) for x in a)
45
>>> # This also works
>>> sum(map(sum, a))
45
>>>
If you want them, here is a reference on map and one on generator expressions.
Here's another answer that hasn't yet been proposed:
from itertools import chain
a = ([1,2,3],[4,5,6],[7,8,9])
sum(chain(*a))
This uses sum with itertools.chain():
Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence. Equivalent to:
def chain(*iterables): # chain('ABC', 'DEF') --> A B C D E F for it in iterables: for element in it: yield element
By passing *a to chain, a is expanded so that its members become the arguments to chain
sum(chain([1,2,3], [4,5,6], [7,8,9])
And we end up with a flattened list (well, iterable actually), equivalent to
sum([1, 2, 3, 4, 5, 6, 7, 8, 9])
print reduce (lambda x, y: x + y, map(sum,a))
map(sum, a) gives: [6, 15, 24]
lambda x,y: x + y is a function which adds the inputs x, y
reduce sums the entries together to get 45.
Additionally, sum(map(sum,a)) will also work, based on the same premise, with simpler syntax, but reduce and lambda are good things to know nonetheless.
reduce(lambda total,next: total+sum(next), a, 0)map? I'm a fan, and it's good to get used to the map-reduce paradigm.map on python builds a new list which can be slow and a bit of a memory hog. Still I agree it is simpler.map, probably for the better.