0

I was expected to see the "0" value, which represented the information of that iteration, printed to the screen.

However, it just showed the last "i" value of the for loop, in my case is "2".

I have been trying for a long time to figure out the answer. During the testing process, I found it might be related to the changing of the variable "i", but I still don't know how to fix it.

So how can I access to the i value of that iteration?

This is my code:

class A:
    def __init__(self, func):
        self.func = func
    def call(self):
        self.func()

xs = []

for i in range(3):
    x = A(lambda: print(i))
    xs.append()

xs[0].call()

The result I got: 2

The result I want: 0

William
  • 3
  • 1
  • `i = 1; def foo(): print(i); i = 2; foo()`… same thing. The function references `i`, not `1`. – deceze May 31 '21 at 06:31

1 Answers1

1

I modified you code and got 0 as output.

class A:
    def __init__(self, func):
        self.func = func
    def call(self):
        self.func()

xs = []

for i in range(3):
    y= A(lambda x=i: print(x)) #== changes here
    xs.append(y)

xs[0].call()