I’m working with python and trying to isolate a problem I had with lambda functions.
From the following code I was expecting to create two lambda functions, each getting a different x, and the output should be
1
2
but the output is
2
2
Why?
And how can I make two different functions? Using def?
def main():
d = {}
for x in [1,2]:
d[x] = lambda: print(x)
d[1]()
d[2]()
if __name__ == '__main__':
main()
The body of the
lambdain your code references the namex. The value associated with that name is changed on the next iteration of the loop, so when the lambda is called and it resolves the name it obtains the new value.To achieve the result you expected, bind the value of
xin the loop to a parameter of thelambdaand then reference that parameter, as shown below: