Search code examples
pythonpython-3.xlambda

Problems with lambda in Python


I have a simple function called return_funcs here:

>>> def return_funcs():
...     functions = []
...     for i in range(4):
...             functions.append(lambda: i)
...     return functions

And when I use return_funcs this is what I get:

>>> for func in return_funcs():
...     func()
...
3
3
3

I was expecting something like:

1
2
3

Why do I get this unexpected output, and how can I fix it?


Solution

  • Python is a lazy language, so the i in your lambda will not be evaluated until you print it. At that point the loop is finished and i kept the last value 3.

    To get your wanted output, use lambda i=i: i. This will create an i variable local to each lambda and assign the current i value to it.