If you know that the lists will be the same length, you can do this:
AB = [A[i] + B[i] for i in range(len(A))]
In Python 2, you can use xrange
instead of range
if your lists are large enough. I think an explicit, simple, readable, obvious way , but some may differ.
If the lists can have different lengths, you need to decide how you want to handle additional elements. Let's say you want to ignore the extra elements of which list is larger. Here are three ways to do this:
AB = [A[i] + B[i] for i in range(min(len(A), len(B)))] AB = map(sum, zip(A, B)) AB = [a + b for a, b in zip(A, B)]
The disadvantage of using zip
is that it will allocate a list of tuples, which can be a large amount of memory if your lists are already large. Using for i in xrange
with a subscription will not allocate all this memory, or you can use itertools.izip
:
import itertools AB = map(sum, itertools.izip(A, B))
If you want to pretend that the shorter list is filled with zeros, using itertools.izip_longest
is the shortest answer:
import itertools AB = map(sum, itertools.izip_longest(A, B, fillvalue=0))
or
import itertools AB = [a + b for a, b in itertools.izip_longest(A, B, fillvalue=0)]