0

I have some problem understanding lambda. My point is adding 1 to a variable in lambda until some point. Example;

x = 0
t = lambda y: y+1

while True:
    print ("Hello")
    t(x)
    if x==5: break

I thought it will stop after 5 times, but I realized that lambda is adding 1 only once. And this while loop is infinite. Why is that? Why lambda doesn't add 1 to that variable until while loop is finish like x += 1 ?

GLHF
  • 3,835
  • 10
  • 38
  • 83

1 Answers1

10

You need to assign the output of t to x. What you did now is like doing:

def t(y):
    return y+1

x = 0
t(x)

Instead of

x = t(x)

You need to do:

x = 0
t = lambda y: y+1

while True:
    print ("Hello")
    x = t(x)
    if x==5: break
olofom
  • 6,233
  • 11
  • 37
  • 50