0

I am trying to dynamically create functions in the following way:

a = []
for i in range(2):
    a.append(lambda: i)
print(a[0](), a[1]())

The results surprised me at first: 1 1. My expectations were that 0 1 would be printed since the first function was created with i = 0 and the second one with i = 1. Then I realized that i is a global variable, thus the result. My questions are:

  • Is there a way to create functions dynamically so that they would print 0 1?
  • Is there something I misinterpret in the code?

Thank you in advance!

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
BillTheKid
  • 377
  • 1
  • 13

0 Answers0