value isn't remembered in lambda python 1

value isn’t remembered in lambda python

def main():
    d = {}
    for x in [1,2]:
        d[x] = lambda x=x: print(x)

    d[1]()
    d[2]()


if __name__ == '__main__':
    main()

>>> 
1
2

Here is what the above code is Doing:
1. The first time through the loop, x is 1.
2. The lambda is created with x=1.
3. The lambda is stored in the dictionary with key 1.
4. The second time through the loop, x is 2.
5. The lambda is created with x=2.
6. The lambda is stored in the dictionary with key 2.
7. The lambda stored with key 1 is called.
8. The lambda stored with key 2 is called.

Similar Posts