2 ms·
I have run into this problem in Python too, but not recently. I'm not sure if Python has changed or if I just caught on to the problem. This should be enough t
by kzrdude 3y ago
I have run into this problem in Python too, but not recently. I'm not sure if Python has changed or if I just caught on to the problem.
This should be enough to show that it still can wind up as a problem in Python:
funcs = [(lambda: x) for x in range(3)]
funcs[0]() # outputs: 2
- paulddraper 3y agoThat is correct. Python used to be worse; it used to share scope outside the list comprehension.
- nightfly 3y agoIt still does for regular loops right?
- thatguysaguy 3y agoYeah loops don't get their own scopes (unless you add one using this thing I made as a joke: https://github.com/davisyoshida/360blockscope https://github.com/davisyoshida/360blockscope)
- pulvinar 3y agoGPT-4 says: The behavior you're observing is due to the late binding nature of closures in Python. When you use a lambda inside a list comprehension (or any loop), it captures a reference to the variable x, not its current value. By the time you call funcs[0](), x has already been set to the last value in the range, which is 2. To get the desired behavior, you can pass x as a default argument to the lambda: funcs = [(lambda x=x: x) for x in range(3)] funcs[0]() # outputs 0