Home > Backend Development > Python Tutorial > Why Do Python Lambda Functions Capture Values, Not References, and How Can This Be Resolved?

Why Do Python Lambda Functions Capture Values, Not References, and How Can This Be Resolved?

Barbara Streisand
Release: 2024-12-27 10:18:10
Original
530 people have browsed it

Why Do Python Lambda Functions Capture Values, Not References, and How Can This Be Resolved?

Understanding Closure Captures in Lambda Functions

Python closures capture the state of the enclosing scope where they are defined. Specifically, they capture the values of variables referenced within the lambda function that are not present in its scope.

In the example provided, the lambda functions capture the variable i, which is assigned different values as the loop executes. However, the lambda functions do not capture a reference to the object pointed to by i. Instead, they capture the value of i at the time of their creation.

This behavior explains the unexpected result of 6 when calling adders[1](3). Despite the expectation of a reference to the integer object, the lambda function captures the value 3, which is the final value assigned to i.

To achieve the desired behavior of preserving the current value of i in each lambda function, a technique called argument defaults can be employed. By providing a default argument to the lambda function, the value of i at the time of creation is locked in. For example:

for i in [0, 1, 2, 3]:
   adders[i] = lambda a, i=i: i+a
Copy after login

In this case, the parameter i has a default value set to the current value of i. When the lambda function is invoked, it uses the value of i that was captured during its creation.

This method ensures that each lambda function in the adders array captures the intended value of i, allowing them to produce the expected output when invoked.

The above is the detailed content of Why Do Python Lambda Functions Capture Values, Not References, and How Can This Be Resolved?. For more information, please follow other related articles on the PHP Chinese website!

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