2

I'm sure there is a good way to accomplish what i want without looping over lists and creating new objects. Here is what I have

a = [1, 2, 3, 4]
b = [2, 3, 4, 5]

What I am looking to do is take each set of lists and sum each placeholder so that the output is

[3, 5, 7, 9]

Thoughts?

Adam Hopkins
  • 6,837
  • 6
  • 32
  • 52
  • 1
    So, is an [element-wise sum](http://stackoverflow.com/questions/18713321/element-wise-addition-of-2-lists-in-python) what you're looking for? – Alex Riley Apr 29 '15 at 14:12
  • The `map` method doesn't return a `list` anymore in python3. You would have to call `list(map(...))` to get a list back again. – Bhargav Apr 29 '15 at 14:15

2 Answers2

4

you should use zip function and list comprehension

a = [1, 2, 3, 4]
b = [2, 3, 4, 5]
[sum(t) for t in zip(a,b)]
Jose Ricardo Bustos M.
  • 8,016
  • 6
  • 40
  • 62
2

Use numpy

import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([2, 3, 4, 5])
a+b
>>> array([3, 5, 7, 9])
DilithiumMatrix
  • 17,795
  • 22
  • 77
  • 119