-2
def printName(name):
    print(name)

if __name__ == "__main__":
    lambdaList = []
    for i in range(4):
        lambdaList.append(lambda : printName(i))
        lambdaList[0]()

I have just learned lambda function. In this case I would like to define different lambda functions like above. However, the result of this script is:

0
1
2
3

I'm a little bit confused about this result. Why is the first lambda function changed when I append new elements to this list. I wish someone can help me.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Fu Xihao
  • 1
  • 2

1 Answers1

0

It's because the i in the lambda is the same i in memory as the one being updated by the for loop.

Ruzihm
  • 19,749
  • 5
  • 36
  • 48