0

I want to create a list of lambda functions which I create inside a for loop and append it to the list. My problem is that the append command seems to overwrite all previous list entries.

The problem can be reproduced with the following code

func_list = []
for i in range(4):
    func_list.append(lambda x: i)
    print func_list[-1](0)

print '**********'

for f in func_list:
    print f(0)

The print command inside the first for loop produces the expected output (0, 1, 2, 3). However, the second for loop prints 3 for all elements of the list (3, 3, 3, 3).

How can I understand this behavior and how can I solve my problem?

Daniel
  • 213
  • 1
  • 2
  • 5
  • 1
    Also http://stackoverflow.com/questions/233673/lexical-closures-in-python – Moses Koledoye Jul 11 '16 at 16:03
  • 1
    That's because you're passing the `i` throw away variable to your `lambda` function which holds the last items of the range in last iteration, therefor all of the `i`'s within your functions will return the last item in range which is 3. – Mazdak Jul 11 '16 at 16:03
  • Thanks for the comments. I was able to solve the problem to create a new scope with a function creator function inside the for loop. – Daniel Jul 11 '16 at 16:21

0 Answers0