2

Suppose I have the following code

callbacks = []
for i in range(10):
    callbacks.append(lambda x: i)

all functions in callbacks will return the final value of i. How can I create callbacks that return the current value for i at creation time?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
duckworthd
  • 14,679
  • 16
  • 53
  • 68

2 Answers2

6
for i in range(10):
  callbacks.append(lambda x = i : x)
gefei
  • 18,922
  • 9
  • 50
  • 67
3
In [113]: callbacks=[]

In [114]: for i in range(10):
    callbacks.append(lambda x=i:x**2)
   .....:     
   .....:     

In [117]: callbacks[0]()
Out[117]: 0

In [118]: callbacks[1]()
Out[118]: 1

In [119]: callbacks[2]()
Out[119]: 4

In [120]: callbacks[4]()
Out[120]: 16
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504