Why do Python lambdas inside a loop all use the last value of the loop variable?
04:00 14 May 2026
I am trying to create a list of functions dynamically. Each function should multiply a number by a different value.

Here is my code:

```python
funcs = []

for i in range(5):
    funcs.append(lambda x: x * i)

for f in funcs:
    print(f(10))

I expected the output to be:

0
10
20
30
40

But the actual output is:

40
40
40
40
40

I understand that lambda x: x * i creates a function, and I thought each function would remember the value of i at the time it was created.

However, it seems that all functions use the final value of i after the loop ends.

Why does this happen in Python? Is this related to closures or late binding? What is the correct way to create these functions so that each one keeps its own value of i?

python pandas