Home > Backend Development > Python Tutorial > How to Properly Capture Variables in Lambda Functions in Loops?

How to Properly Capture Variables in Lambda Functions in Loops?

Susan Sarandon
Release: 2024-10-19 17:26:02
Original
670 people have browsed it

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:

<code class="python">for m in ('do', 're', 'mi'):
    funcList.append(lambda: callback(m))</code>
Copy after login

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>
Copy after login

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!

source:php
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