0

I need to zip two lists inclusively. I.e. keep values of the longer list and, possibly, add a default value for the shorter one:

e.g.

lst_a = [1,2,3]  # len = 3
lst_b = [5,6,7,8]  # len = 4

# no default values
inclusive_zip(lst_a, lst_b) = [(1,5),(5,6),(3,7),(None,8)]

# with default value (e.g. for position in 2D space)
inclusive_zip(lst_a, 0, lst_b, 0) = [(1,5),(5,6),(3,7),(0,8)]

I can make something of my own, but was wondering if there's a built-in or super simple solution.

ofer.sheffer
  • 5,417
  • 7
  • 25
  • 26
  • 1
    Possible duplicate of [Outerzip / zip longest function (with multiple fill values)](https://stackoverflow.com/questions/13085861/outerzip-zip-longest-function-with-multiple-fill-values) or [Python: zip-like function that pads to longest length?](https://stackoverflow.com/questions/1277278/python-zip-like-function-that-pads-to-longest-length#1277311) – fredtantini Sep 18 '17 at 08:44

1 Answers1

0

itertools.zip_longest(*iterables, fillvalue=None)

import itertools

def add_by_zip(p1,p2):
    p_out = [a+b for a,b in itertools.zip_longest(p1,p2, fillvalue=0)]
    print(p_out)
ofer.sheffer
  • 5,417
  • 7
  • 25
  • 26