Issue
I'm trying to understand the lambda function in python and got this.
When I store the instance of lambda function in a Dict. It gives the expected result inside of the loop. But outside of the loop, it always stored the last instance, I think.
Can someone explain why this happening? and how the lambda function actually works when we store their instance.
Code:
d = {}
for x in range(4):
d[x] = lambda n: str(n*x)
print(d[x](1))
print(d[1](2))
print(d[2](2))
print(d[3](2))
Output:
0
1
2
3
6
6
6
Solution
given some x
these 2 functions are equivalent:
f1 = lambda n: str(n * x)
def f2(n):
return str(n * x)
all you are doing in addition to that is to put several functions (for several values of x
) in a dictionary.
Answered By - hiro protagonist
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.