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
Linda HamiltonOriginal
2024-12-06 02:29:10516browse

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)
    )

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)
    )

Alternatively, lambda expressions can be rewritten as follows:

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

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!

Statement:
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