Oct-03-2018, 04:48 PM
I don't know how to explain it very well, but I've been trying to figure this out for a few days and I haven't had any luck with fixing it.
The following code is supposed to append a lambda to a list, so that the function the lambda calls can be called later on. NOTE: this isn't my actual code, but a proof of concept that works in the same way.
The following code is supposed to append a lambda to a list, so that the function the lambda calls can be called later on. NOTE: this isn't my actual code, but a proof of concept that works in the same way.
def foo(bar): print(bar) li = [] for i in range(10): li.append(lambda: foo(i))Later I can call the functions using this chunk of code.
for func in li: func()When I run this, instead of steadily incrementing, it just uses the last value of i.
Output:9
9
9
9
9
9
9
9
9
9
I understand that this is due to how python handles variable referencing, but I want to know if there is a way to bypass this and only get the value of i without referencing it.