Home >Backend Development >Python Tutorial >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!