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:
<code class="python">for m in ('do', 're', 'mi'): funcList.append(lambda: callback(m))</code>
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":
<code class="python">for m in ('do', 're', 'mi'): funcList.append(lambda m=m: callback(m))</code>
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"
The above is the detailed content of How to Properly Capture Variables in Lambda Functions in Loops?. For more information, please follow other related articles on the PHP Chinese website!