Home >Backend Development >Python Tutorial >Why Do Lambdas in Loops Capture the Last Value, and How Can This Be Avoided?
Lambda in For Loop Captures Last Value
In your code:
for i in range(len(options)): option = options[i] __cMenu.add_command( label="{} ".format(option), command=lambda: self.filter_records(column, option) )
each lambda captures the variable option, which is evaluated when the lambda function is created. This means all lambdas capture the same value of option, which is the last value it takes on in the loop.
To avoid this, you need to ensure that each lambda captures a different value of option. This can be done by using the lambda syntax with an optional parameter, like so:
for i in range(len(options)): option = options[i] __cMenu.add_command( label="{} ".format(option), command=lambda opt=option: self.filter_records(column, opt) )
In this case, the lambda function captures the value of option as the parameter opt, ensuring that each lambda captures a different value of option.
The above is the detailed content of Why Do Lambdas in Loops Capture the Last Value, and How Can This Be Avoided?. For more information, please follow other related articles on the PHP Chinese website!