For the purpose of this post, I've handcrafted a silly example, but what I'm interested in, is the underlying concept, so alternative solutions to this particular problem are not what I'm looking for. I've tried multiple times to find any similar thread but honestly, its hard to word this particular question. So here we go...
The following code:
lambdas = []
for i in range(5):
lambdas.append(lambda:i)
for l in lambdas:
print(l())
yields:
4
4
4
4
4
Which means, each element of the lambda list will always return the current value of i
My cheap workaround is:
lambdas = []
for i in range(5):
lambdas.append(eval("lambda:{}".format(i)))
for l in lambdas:
print(l())
which yields the desired:
0
1
2
3
4
However it is my understanding that it is best to avoid eval
statements whenever possible.
So my question is: Is there a better workaround to achieve the same result (while still using lambda expressions)?