Python lambda doesn't remember argument in for loop

Viewed 4452

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()
3 Answers
Related