Home > Backend Development > Python Tutorial > Why Do Lambdas in Loops Capture the Last Value, and How Can This Be Avoided?

Why Do Lambdas in Loops Capture the Last Value, and How Can This Be Avoided?

Patricia Arquette
Release: 2024-12-23 17:01:09
Original
161 people have browsed it

Why Do Lambdas in Loops Capture the Last Value, and How Can This Be Avoided?

Lambda in For Loop Captures Last Value

In your code:

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

each lambda captures the variable option, which is evaluated when the lambda function is created. This means all lambdas capture the same value of option, which is the last value it takes on in the loop.

To avoid this, you need to ensure that each lambda captures a different value of option. This can be done by using the lambda syntax with an optional parameter, like so:

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

In this case, the lambda function captures the value of option as the parameter opt, ensuring that each lambda captures a different value of option.

The above is the detailed content of Why Do Lambdas in Loops Capture the Last Value, and How Can This Be Avoided?. 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