I want to parse 2 generators of (potentially) different length with zip
:
for el1, el2 in zip(gen1, gen2):
print(el1, el2)
However, if gen2
has less elements, one extra element of gen1
is "consumed".
For example,
def my_gen(n:int):
for i in range(n):
yield i
gen1 = my_gen(10)
gen2 = my_gen(8)
list(zip(gen1, gen2)) # Last tuple is (7, 7)
print(next(gen1)) # printed value is "9" => 8 is missing
gen1 = my_gen(8)
gen2 = my_gen(10)
list(zip(gen1, gen2)) # Last tuple is (7, 7)
print(next(gen2)) # printed value is "8" => OK
Apparently, a value is missing (8
in my previous example) because gen1
is read (thus generating the value 8
) before it realizes gen2
has no more elements. But this value disappears in the universe. When gen2
is "longer", there is no such "problem".
QUESTION: Is there a way to retrieve this missing value (i.e. 8
in my previous example)? ... ideally with a variable number of arguments (like zip
does).
NOTE: I have currently implemented in another way by using itertools.zip_longest
but I really wonder how to get this missing value using zip
or equivalent.
NOTE 2: I have created some tests of the different implementations in this REPL in case you want to submit and try a new implementation :) https://repl.it/@jfthuong/MadPhysicistChester