Home > Backend Development > Python Tutorial > Why Do My Lambda Functions in a Loop All Refer to the Same Variable?

Why Do My Lambda Functions in a Loop All Refer to the Same Variable?

Barbara Streisand
Release: 2024-12-29 03:45:10
Original
966 people have browsed it

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)
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template