Home > Backend Development > Python Tutorial > Why Do Lambda Functions in Python For Loops Only Capture the Last Value?

Why Do Lambda Functions in Python For Loops Only Capture the Last Value?

Linda Hamilton
Release: 2024-12-06 02:29:10
Original
503 people have browsed it

Why Do Lambda Functions in Python For Loops Only Capture the Last Value?

Lambda in for Loop Only Takes Last Value

When employing lambda functions within a for loop, the value captured by the lambda may not be the intended one. This issue arises due to how Python's garbage collection operates, causing only the last value of the variable to be retained.

To illustrate this concept:

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

In this code, each lambda function should capture a unique value of option, but all will behave as if option were set to "DEBUG," the final value it assumes in the loop.

To resolve this issue, as suggested in the solution, each lambda function must capture its own variable. This can be achieved by assigning a new local variable to option, as follows:

for i in range(len(options)):
    opt = options[i]  # Assign a new variable to capture the unique value
    __cMenu.add_command(
        label="{}".format(opt),
        command=lambda: self.filter_records(column, opt)
    )
Copy after login

Alternatively, lambda expressions can be rewritten as follows:

lambda opt=option: self.filter_records(column, opt)  # Differentiate loop variable and function parameter
Copy after login

By capturing the appropriate values, lambda functions can function independently within a loop, allowing for the intended behavior to be achieved.

The above is the detailed content of Why Do Lambda Functions in Python For Loops Only Capture 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