Home > Backend Development > Python Tutorial > Why Do Lambda Functions in Loops Capture the Last Value Instead of Each Iteration's Value?

Why Do Lambda Functions in Loops Capture the Last Value Instead of Each Iteration's Value?

Susan Sarandon
Release: 2024-12-21 07:52:10
Original
374 people have browsed it

Why Do Lambda Functions in Loops Capture the Last Value Instead of Each Iteration's Value?

Lambda in a Loop

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

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

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

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!

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