-1

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
Milon Mahato
  • 180
  • 1
  • 12
  • 1
    `str(n*x)` multiplies `n` by `x` with _whatever the value of `x` is at the time you execute this code._ – deceze Apr 28 '22 at 07:35
  • 1
    You meant to write: `d[x] = lambda n, x=x: str(n*x)`. This captures `x` each time round the loop instead of the last value that `x` has after the loop. – quamrana Apr 28 '22 at 07:37

1 Answers1

1

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.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111