2

In Python, is there a good way to add/sum (or otherwise combine) two lists of uneven length?

e.g. given some lists:

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

produce list c:

c = [2,4,6,4]

where each element is the sum of a and b, taking a missing element as zero?

Craig Ringer
  • 307,061
  • 76
  • 688
  • 778

3 Answers3

10

Yes, you can use itertools.zip_longest():

>>> from itertools import zip_longest
>>> a = [1, 2, 3]
>>> b = [1, 2, 3, 4]
>>> [x + y for x, y in zip_longest(a, b, fillvalue=0)]
[2, 4, 6, 4]
Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
2

Here's what I landed up using:

[ (ax or 0) + (bx or 0) for (ax, bx) in map(None, a, b) ]

where n or 0 is used to coalesce None to zero, and map(None, a, b) is used as a null-expanding version of zip.

Problems? Better answers?

Community
  • 1
  • 1
Craig Ringer
  • 307,061
  • 76
  • 688
  • 778
  • 2
    Just note that the `map(None)` trick only works in Python 2.x; for 3.x, you should use `itertools.zip_longest` as in @ZeroPiraeus's answer. – Mark Reed Sep 30 '14 at 01:59
0

Another option:

In [1]: a = [1, 2, 3]
In [2]: b = [1, 2, 3, 4]
In [3]: [i+ii if i and ii else i or ii for (i,ii) in map(lambda x,y: (x,y),a,b)]
Out[3]: [2, 4, 6, 4]
aabilio
  • 1,697
  • 12
  • 19