Home  >  Article  >  Backend Development  >  Why Does the Scope of Lambda Functions Impact Their Output in Python?

Why Does the Scope of Lambda Functions Impact Their Output in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-10-19 17:26:30949browse

Why Does the Scope of Lambda Functions Impact Their Output in Python?

Scope of Lambda Functions and Their Parameters

In Python, lambda functions provide shorthand notation for defining inline functions. However, their scope and parameter handling can lead to unexpected behavior, as demonstrated by the following code:

def callback(msg):
    print msg

# Iterative Approach
funcList = []
for m in ('do', 're', 'mi'):
    funcList.append(lambda: callback(m))
for f in funcList:
    f()

# Individual Creation
funcList = []
funcList.append(lambda: callback('do'))
funcList.append(lambda: callback('re'))
funcList.append(lambda: callback('mi'))
for f in funcList:
    f()

The expected output is:

do
re
mi
do
re
mi

However, the actual output is:

mi
mi
mi
do
re
mi

This behavior stems from the fact that lambda functions do not create copies of variables from the enclosing scope. Instead, they maintain references to those variables. As a result, changes to the value of m in the loop affect all lambda functions created within that loop.

To resolve this issue, it is common practice to capture the value of m at the time of lambda function creation by using it as the default argument of an optional parameter:

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

This ensures that each lambda function captures the correct value of m, resulting in the desired output:

do
re
mi
do
re
mi

The above is the detailed content of Why Does the Scope of Lambda Functions Impact Their Output in Python?. 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