Home > Backend Development > Python Tutorial > Why Do Functions Created in a Python Loop All Return the Same Value?

Why Do Functions Created in a Python Loop All Return the Same Value?

DDD
Release: 2024-12-22 01:57:14
Original
655 people have browsed it

Why Do Functions Created in a Python Loop All Return the Same Value?

Function and Lambda Creation Anomalies in Loops

When attempting to generate functions within a loop, as seen in the code snippet below, a peculiar issue arises:

functions = []

for i in range(3):
    def f():
        return i
    functions.append(f)
Copy after login

Similarly, when using lambdas:

functions = []

for i in range(3):
    functions.append(lambda: i)
Copy after login

One would expect these functions to output distinct values (0, 1, and 2), but all functions end up yielding the same value (2).

Explanation and Solution

This phenomenon is caused by late variable binding. In Python functions, variables are resolved when called, which means that when the functions are invoked after the loop, the value of i is already set to 2. To rectify this, we employ early binding by introducing the f(i=i) syntax. Here, the default value for the i argument is established at the time of definition, resulting in early binding:

def f(i=i):
    return i
Copy after login

Alternatively, a more complex approach using a closure and a "function factory" ensures early binding as well:

def make_f(i):
    def f():
        return i
    return f
Copy after login

Within the loop, we can then utilize f = make_f(i) rather than the def statement.

The above is the detailed content of Why Do Functions Created in a Python Loop All Return the Same Value?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template