0

I'm trying to make a list of objects in python that each own 2 values: text, func text is just a name assigned to it and func is a lambda function, all the code is a part of my project so I tried to represent that code section in a short code piece

l = []
for i in range(3):
    l.append(lambda: i)
for j in l:
    print(j())

now the output is

2
2
2

I understand that the output is all 2's because that's the last 'i' defined but I want the output to be:

0
1
2

without changing 'j' to 'i' (because I already know it will work and in my project I have no control over 'j') in short, my question is: how do i make the lambda function to save the current 'i' instead of looking for the last 'i' defined

martineau
  • 119,623
  • 25
  • 170
  • 301
avi
  • 1

0 Answers0