14

Is there an easy way to compute the element-wise sum of N lists in python? I know if we have n lists defined (call the ith list c_i), we can do:

z = [sum(x) for x in zip(c_1, c_2, ...)]

For example:

c1 = [1,2]
c2 = [3,4]
c3 = [5,6]
z  = [sum(x) for x in zip(c1,c2,c3)]

Here z = [9, 12]

But what if we don't have c_i defined and instead have c_1...c_n in a list C?

Is there a similar way to find z if we just have C?

I hope this is clear.

resolved: I was wondering what the * operator was all about...thanks!

2 Answers2

37

Just do this:

[sum(x) for x in zip(*C)]

In the above, C is the list of c_1...c_n. As explained in the link in the comments (thanks, @kevinsa5!):

* is the "splat" operator: It takes a list as input, and expands it into actual positional arguments in the function call.

For additional details, take a look at the documentation, under "unpacking argument lists" and also read about calls (thanks, @abarnert!)

Community
  • 1
  • 1
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • 2
    http://stackoverflow.com/questions/5239856/foggy-on-asterisk-in-python Shows what the asterisk does. I didn't know that was a thing. – kevinsa5 Oct 09 '13 at 02:03
  • 1
    Didn't some spoilsport go through and remove all references to the name "splat" anywhere in the docs somewhere around 2.5 or 2.6/3.0? Anyway, the tutorial section is ["Unpacking Argument Lists"](http://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists), and the reference is [Calls](http://docs.python.org/3/reference/expressions.html#calls). – abarnert Oct 09 '13 at 02:15
  • 2
    Very nice and pythonic! – Josha Inglis Oct 09 '13 at 02:21
  • does this only work for integers and because it breaks when I try it with floats. – Roshini May 07 '15 at 16:58
  • @Roshini of course it works with floats, you must be doing something wrong, it's just an addition! check the way you're building the input lists. – Óscar López May 07 '15 at 17:07
  • I tried your method, but it keeps giving me this message: TypeError: 'list' object is not callable – user177196 Aug 29 '17 at 18:10
2

This isn't all that different from Óscar López's answer, but uses itertools.imap instead of a list comprehension.

from itertools import imap
list(imap(sum, zip(*C))
chepner
  • 497,756
  • 71
  • 530
  • 681