Answer the question
In order to leave comments, you need to log in
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.
def makeActions():
acts = []
for i in range(5): # Сохранить каждое значение i
acts.append(lambda x: i ** x) # Все запомнят последнее значение i!
return acts
acts = makeActions()
Answer the question
In order to leave comments, you need to log in
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question