Scope comparison problem with default parameter with loop variable

This question comes from a book "Learning Python, Fourth Edition" written by American author Mark Lutz.

The original text is as follows:

If a lambda or def is defined in a function, nested in a loop, and the nested function references a variable in the upper scope that is changed by the loop variable, all functions generated in the loop variable will be have the same value - the value of the referenced variable when the last loop completed.

Let's look at the next example:

 1 >>> def makeActions():
 2 ...     acts = []
 3 ...     for i in range(5):
 4 ...             acts.append(lambda x: i ** x)
 5 ...     return acts
 6 ... 
 7 >>> acts = makeActions()
 8 >>> acts[0](2)
 9 16
10 >>> acts[1](2)
11 16
12 >>> acts[2](2)
13 16
14 >>> acts[3](2)
15 16
16 >>> acts[4](2)
17 16
>>> def makeActions():
...     acts = []
...     for i in range(5):
...             acts.append(lambda x: i ** x)
...     return acts
...
>>> acts = makeActions()
>>> acts[0](2)
16
>>> acts[1](2)
16
>>> acts[2](2)
16
>>> acts[3](2)
16
>>> acts[4](2)
16

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325093816&siteId=291194637