I'm using list expansion to create a set of lambda functions. Each lambda function returns a generator with an initial value. The API I am using requires that I pass it a 0-parameter function handle that returns a generator object. Hence the odd form of lambda: generator
.
I get unexpected results, shown below. Can anyone explain why I only see the generator seeded with 200
when using list expansion?
All code is copy/paste runnable.
Case 1: Using list expansion
def mygen(val):
for i in range(3):
yield val + i
generators = [lambda: mygen(start) for start in [100, 200]]
g = generators[0]() # generators[1]() produces the same result
for _ in range(3):
print(next(g))
Result:
200
201
202
Expected Result:
100
201
202
Case 2: Without list expansion
def mygen(val):
for i in range(3):
yield val + i
g0 = lambda: mygen(100)
g1 = lambda: mygen(200)
g = g0()
for _ in range(3):
print(next(g))
Result (as expected)
100
101
102