'python: pointwise list sum
Input: two lists (list1, list2) of equal length
Output: one list (result) of the same length, such that:
result[i] = list1[i] + list2[i]
Is there any concise way to do that? Or is this the best:
# Python 3
assert len(list1) == len(list2)
result = [list1[i] + list2[i] for i in range(len(list1))]
Solution 1:[1]
IMO the nicest way is
result = [x + y for x, y in zip(list1, list2)]
with Python3 basic zip is not even building an intermediate list (not an issue unless list1 and list2 lists are huge).
Note however that zip will stop at the shortest of the input lists, so your assert is still needed.
Solution 2:[2]
[a + b for a, b in zip(list1, list2)]
Solution 3:[3]
There are several ways, e.g. using map, sum and izip (but afaik, zip works the same as izip in Python 3):
>>> from itertools import izip
>>> map(sum, izip(list1, list2))
Solution 4:[4]
I'd do:
result = [x+x for x,y in zip(list1, list2)]
Solution 5:[5]
using the + as pointwise sum is the default operation on numpy arrays.
the * operator likewise is the pointwise multiplikation:
import numpy as np
list1 = np.array(list1)
list2 = np.array(list2)
assert list(list1+list2) == list([list1[i] + list2[i] for i in range(len(list1))])
assert list(3*list1) == list([3*list1[i] for i in range(len(list1))])
comparing two list equal with == does not work with np arrays though.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | 6502 |
| Solution 2 | Ignacio Vazquez-Abrams |
| Solution 3 | Felix Kling |
| Solution 4 | vartec |
| Solution 5 | Johann Wiengold |
