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

Barbara Streisand
Release: 2024-10-19 17:26:30
Original
947 people have browsed it

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

The expected output is:

do
re
mi
do
re
mi
Copy after login
Copy after login

However, the actual output is:

mi
mi
mi
do
re
mi
Copy after login

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

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

do
re
mi
do
re
mi
Copy after login
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!