0

i have this code

i = 10
f1 = lambda x1: x1 * i 
i = 20

print(f1(1))

this print me 20 instead of 10, i need to store multiple lambdas functions without changes, but keeping the same name on variables, because I'm storing lambdas functions in a dictionary like this

for j in range(10):
   my_key = j
   my_value = j
   my_dict[my_key] = lambda a: int(a) * int(my_value)

when i use any of this lambdas functions, all of them store the last value of my_value that is 9, but I need the lambda function not to change when changing the value of the variable

what can i do? i cant figure out

  • Lambda expressions behave the same way as `def` statements. They don't capture values at the time they are evaluated; `i` is just a free variable whose lookup is performed when the function is called. The value of `i` when the function is defined is irrelevant. (In fact, `i` doesn't even need to be defined when `f1` is defined, as long as `i` is defined before `f1` is called.) – chepner Oct 29 '21 at 01:00

0 Answers0