4 ms·
One useful case for the existing is to eagerly bind variables: Here's a stupid example. Notice in the first case printing i doesn't grab the value of i when th
by patrickthebold 5y ago
One useful case for the existing is to eagerly bind variables:
Here's a stupid example. Notice in the first case printing i doesn't grab the value of i when the lambda is defined. The second case is likely what you want.
>>> lambdas = [lambda : print(i) for i in range(2)]
>>> for l in lambdas:
... l()
...
1
1
>>> lambdas = [lambda i=i: print(i) for i in range(2)]
>>> for l in lambdas:
... l()
...
0
1
- bjoli 5y agoOh my, that's awful. Even in python there are better ways to close over a value :) I haven't written python in many years, but in the following example it is at least clear what is going on: def make_printer(n): def printer(): print(n) return printer [make_printer(i) for i in range(2)]