0

For example,

a = ([1,2,3],[4,5,6],[7,8,9])

sum returned should = 45

1

6 Answers 6

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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])

2 Comments

Can you explain the chain function? Seems good..
Ya I get it.. Nice function..
1

Use the sum function

s = 0
for i in a:
    s += sum(i)

print s

Comments

1
a = ([1,2,3],[4,5,6],[7,8,9])
total = 0

for i in a:
  total += sum(i)

This assumes that the list only contains lists that are full of numbers. If you want to be smarter than that, you'll need to make a function.

Comments

1
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.

5 Comments

I like the use of reduce, but not such a fan of map. How about reduce(lambda total,next: total+sum(next), a, 0)
@PeterGibson Seems unnecessarily convoluted. What's wrong with 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.
Actually, looks like this is no longer the case in Python 3, so I retract my suggestion :)
@PeterGibson Yeah, they changed map, probably for the better.
0
a = [1,2,3],[4,5,6],[7,8,9]
sum(sum(a, []))

The inner sum flattens the list by adding the sublists to the empty list - equivalent to

sum([] + [1,2,3] + [4,5,6] + [7,8,9])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.