I have a small snippet that does not work in an inexplicable way.
The purpose is to generate all combinations of two or more sequences.
It works when called with lists, but it doesn’t when called with generators.
def comb(seqs):
if seqs:
for item in seqs[0]:
for rest in comb(seqs[1:]):
yield [item] + rest
else:
yield []
if __name__=="__main__":
x=[1,2]
y=[3,4]
print list(comb([x,y])) # prints [[1, 3], [1, 4], [2, 3], [2, 4]]
def gen1(): yield 1; yield 2
def gen2(): yield 3; yield 4
x=gen1()
y=gen2()
print list(comb([x,y])) # prints [[1, 3], [1, 4] WHY ????
The reason is that you can only iterate over a generator once. In the line
When you get to the second element of the
gen1, you make a recursive call to iterate over the elements ofgen2. The problem is that you have already iterated overgen2in the previous recursive call, so it will not yield any items.