A
A
Aitym Ramazanov2015-05-17 13:10:08
Python
Aitym Ramazanov, 2015-05-17 13:10:08

I can not understand something about the closure. Can you help?

Reading the 4th edition of "Learning Python" by M. Lutz. Page 492 says this rule:

if a lambda expression or def statement is nested in a loop within another
function, and the nested function refers to a variable in the enclosing
scope that changes in the loop, all functions created in that
loop will have the same value—a value that had a variable
at the last iteration.

and gives this example:
def makeActions():
    acts = []
        for i in range(5):                                       # Сохранить каждое значение i
            acts.append(lambda x: i ** x)                # Все запомнят последнее значение i!
    return acts

acts = makeActions()

Then it is shown that:
acts[0](2), acts[2](2) and acts[4](2) return 4 ** 2, i.e. 16.
I checked all this, it works exactly as the author says . But here is the question: why is the last value of the for loop, how is it implemented in python

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
vittly, 2015-05-17
@iTeam91

In the acts array, there are essentially the same lambdas - each one has captured the variable i in the closure and returns its doubled value. The last value of i was 4. Accordingly, any of the lambdas returns 16. You need to look at the variable as a memory area, for the variable i it is the same area, no matter from which lambda you access it

S
steel_dog, 2017-02-20
@steel_dog

Thanks for the comments.
And can someone describe in more detail each line in action in words.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question