Home >Backend Development >Python Tutorial >Why Do My Lambda Functions in a Loop All Refer to the Same Variable?
Lambda in a Loop
In the provided code, the intention is to create a dictionary of command functions where each value is a lambda expression that calls self.root.change_directory with a specific directory name. However, the code incorrectly results in all command functions performing the same directory change.
The issue arises because the lambda expressions are referencing a single variable, d, which is the same for each iteration of the loop. Consequently, all lambda expressions end up pointing to the last value of d.
To correct this, it is necessary to bind a unique value of d to each lambda expression. This can be achieved by using a default value for the lambda's parameter, as shown below:
self.command["cd " + d] = lambda d=d: self.root.change_directory(d)
In this case, d=d creates a new binding of d to the current value of d for each iteration of the loop. As a result, each lambda expression has its own unique reference to the d value.
Alternatively, a closure can be used to achieve the same effect:
self.command["cd " + d] = (lambda d: lambda: self.root.change_directory(d))(d)
This closure creates a new environment for each lambda expression, where d is bound to the current value of d. Therefore, each lambda expression has access to its own unique value of d.
The above is the detailed content of Why Do My Lambda Functions in a Loop All Refer to the Same Variable?. For more information, please follow other related articles on the PHP Chinese website!