When employing lambda functions within a for loop, the value captured by the lambda may not be the intended one. This issue arises due to how Python's garbage collection operates, causing only the last value of the variable to be retained.
To illustrate this concept:
options = ["INFO", "WARNING", "DEBUG"] for i in range(len(options)): option = options[i] __cMenu.add_command( label="{}".format(option), command=lambda: self.filter_records(column, option) )
In this code, each lambda function should capture a unique value of option, but all will behave as if option were set to "DEBUG," the final value it assumes in the loop.
To resolve this issue, as suggested in the solution, each lambda function must capture its own variable. This can be achieved by assigning a new local variable to option, as follows:
for i in range(len(options)): opt = options[i] # Assign a new variable to capture the unique value __cMenu.add_command( label="{}".format(opt), command=lambda: self.filter_records(column, opt) )
Alternatively, lambda expressions can be rewritten as follows:
lambda opt=option: self.filter_records(column, opt) # Differentiate loop variable and function parameter
By capturing the appropriate values, lambda functions can function independently within a loop, allowing for the intended behavior to be achieved.
The above is the detailed content of Why Do Lambda Functions in Python For Loops Only Capture the Last Value?. For more information, please follow other related articles on the PHP Chinese website!