Eventually, I arrived at the following generic function:
def zip_shift(s1, s2, shift, placeholder):
i1 = iter(s1)
i2 = iter(s2)
while shift > 0:
yield placeholder, next(i2) # leave only next(i2) if no placeholder pairs are needed
shift -= 1
yield from zip(i1, i2) # or return zip
The above function works like a generator that first fills in the placeholder
values shift
times instead of taking values from the second sequence s2
. Afterward, it works just like zip
. The yield from
is a relatively new construct (since Python 3.3). There are subtle differences between yield from
and return
above but can be neglected in this situation.
Of course if the shift
value is 1 almost (with the exception of the pairs with the placeholder) the same can be achieved with:
zip(s1, next(s2))
As with zip
sequences do not have to be of the same length. The generator works as long as the shorter sequence is not exhausted.