Article From:https://segmentfault.com/q/1010000011702170

Question:

```
def multi():
return [lambda x: i * x for i in range(4)]
print([m(3) for m in multi()])
```

Why is this execution result?

Answer 0:

Chi Bangding of closure variables really calculates the value of I when it is called. In fact, it is equivalent to:

```
def multi():
r = []
for i in range(4):
def f(x):
return i*x
r.append(f)
return r
print([m(3) for m in multi()])
```

If you want the expected results, you can:

```
def multi():
return [lambda x, i=i: i * x for i in range(4)]
print([m(3) for m in multi()])
```

This is equivalent to:

```
def multi():
r = []
for i in range(4):
def f(x, i=i):
return i*x
r.append(f)
return r
print([m(3) for m in multi()])
```

### Similar Posts:

- Python/JS closure
- Python/JS closure
- 09 anonymous functions, function scopes, closures, recursion
- 09 anonymous functions, function scopes, closures, recursion
- Python entry sixteenth days anonymous function, return function, closure
- Python entry sixteenth days anonymous function, return function, closure
- python 11
- The usage of range () function in Python
- The usage of range () function in Python
- About closure experience

Link of this Article: Anonymous function, list generation