"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Properly Capture Variables in Lambda Functions in Loops?

How to Properly Capture Variables in Lambda Functions in Loops?

Published on 2024-11-07
Browse:165

How to Properly Capture Variables in Lambda Functions in Loops?

Capturing Variables in Lambda Functions

When using lambda functions within a loop, it's important to understand their variable scope. Unlike regular functions which copy local variables, lambda functions reference them.

Consider the given code:

for m in ('do', 're', 'mi'):
    funcList.append(lambda: callback(m))

Here, the lambda function captures the value of m from the enclosing scope. However, after the loop finishes, m retains the last value ('mi'). When each lambda function is called, it references this shared m variable, resulting in the output "mi" multiple times.

To overcome this issue and ensure each lambda captures a distinct value of m, use a technique called "default arguments":

for m in ('do', 're', 'mi'):
    funcList.append(lambda m=m: callback(m))

By making m a default parameter with the same name, each lambda captures its own instance of the variable, ensuring the expected output:

"do"
"re"
"mi"

Release Statement This article is reprinted at: 1729329734 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3