Home > Backend Development > Python Tutorial > Why Do My Lambdas in a For Loop Only Use the Last Value?

Why Do My Lambdas in a For Loop Only Use the Last Value?

Mary-Kate Olsen
Release: 2024-12-18 06:17:10
Original
222 people have browsed it

Why Do My Lambdas in a For Loop Only Use the Last Value?

Lambda in For Loop Only Takes Last Value

In the following code:

options=["INFO", "WARNING", "DEBUG"]

for i in range(len(options)):
    option=options[i]
    __cMenu.add_command(
        label="{}".format(option), 
        command=lambda: self.filter_records(column, option)
   )
Copy after login

several lambdas are created and saved. These lambdas should capture different values of the local variable option. However, when these lambdas are used, they all behave as though option was set to "DEBUG", the last value it takes on in the loop.

This issue arises due to the evaluation timing of names in function bodies. In the provided code, the names are evaluated when the function is executed. As a result, the lambdas created in the loop all refer to the same value of option at the time of execution, which is "DEBUG".

To circumvent this problem, the following modification can be made:

__cMenu.add_command(label="{}".format(option),
    command=lambda opt=option: self.filter_records(column, opt))
Copy after login

By introducing option=option as an argument to the lambda function, each lambda captures the correct value of option at the time of creation, rather than relying on the value at the time of execution. This ensures that each lambda operates on the desired value of option.

The above is the detailed content of Why Do My Lambdas in a For Loop Only Use the Last 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