Home >Backend Development >Python Tutorial >Why Do Lambda Functions in Loops Capture the Last Value Instead of Each Iteration's Value?
Consider the following code snippet:
# directorys == {'login': <object at ...>, 'home': <object at ...>} for d in directorys: self.command["cd " + d] = (lambda : self.root.change_directory(d))
The goal is to create a dictionary of two functions with keys "cd login" and "cd home". However, the result shows that both lambda functions have the same content with key "cd login".
To understand this unexpected behavior, it's important to consider how lambda functions work in nested loops. When a lambda function is defined within a loop, it captures variables from the surrounding scope. In this case, the variable d from the loop is captured by each lambda function.
However, lambda functions are executed lazily. So, when you access the self.command dictionary outside of the loop, all lambda functions have captured the same d variable, which is the last value of d in the loop. Hence, all functions point to the same method, resulting in the observed behavior.
To solve this issue, we need to ensure that each lambda function captures a distinct value of d. One solution is to pass d as a parameter to the lambda function and provide a default value:
lambda d=d: self.root.change_directory(d)
Now, the d inside the lambda function uses the parameter, even though it has the same name. The default value for this parameter is evaluated when the function is created, binding it to the correct value of d for each iteration of the loop.
Alternatively, we can use nested closures to achieve the same result:
(lambda d: lambda: self.root.change_directory(d))(d)
The above is the detailed content of Why Do Lambda Functions in Loops Capture the Last Value Instead of Each Iteration's Value?. For more information, please follow other related articles on the PHP Chinese website!