Iam trying to learn lambda expressions and came across the below :
funcs = {
idx: lambda: print(idx) for idx in range(4)
}
funcs[0]()
did not understand what is meant by funcs[0] ? Why the index and 0 ?
Iam trying to learn lambda expressions and came across the below :
funcs = {
idx: lambda: print(idx) for idx in range(4)
}
funcs[0]()
did not understand what is meant by funcs[0] ? Why the index and 0 ?
This is a cool example to show how binding and scope work with lambda functions. As Daniel said, funcs
is a dictionary of functions with four elements in it (with keys 0,1,2 and 3). What is interesting is that you call the function at key 0, you expect the index (idx
) that was used to create that key to then print out and you'll get 0. BUT I believe if you run this code, you actually print 3! WHAT!?!? So what is happening is that the lambda function is actually not binding the value of 0 when it stores the reference to the function. That means, when the loop finishes, the variable idx
has 3 associated with it and therefore when you call the lambda function in position 0, it looks up the reference to the variable idx
and finds the value 3
and then prints that out. Fun :)
That was referring more to your question title than to the test... The 0 is to access the function that has key 0 in the dictionary.