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?