Home >Backend Development >Python Tutorial >Why Do Lambda Functions in Loops Only Return the Last Value?
Lambda in For Loop Only Takes Last Value
The issue at hand arises when utilizing lambda functions within a for loop that should capture distinct values of a local variable. However, it is observed that when these lambdas are invoked, they consistently return the final value assigned to the local variable, despite it changing within the loop.
Understanding the Issue
This perplexing behavior stems from the evaluation timing of lambda functions. Specifically, the names employed within lambda function bodies are evaluated when the function is executed, not at the time of its definition.
Solution
To resolve this issue, it is essential to capture the local variable's value at the moment of lambda definition, not when it is invoked. One approach is to declare the variable you intend to capture as an argument to the lambda function.
options = ["INFO", "WARNING", "DEBUG"] for i in range(len(options)): option = options[i] __cMenu.add_command(label="{}".format(option), command=lambda opt=option: self.filter_records(column, opt))
By setting "option=option" before the colon, we are explicitly assigning the value of "option" as an argument to the lambda function, ensuring that each lambda captures the intended value.
The above is the detailed content of Why Do Lambda Functions in Loops Only Return the Last Value?. For more information, please follow other related articles on the PHP Chinese website!