1

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?

abhigyanj
  • 2,355
  • 2
  • 9
  • 29

1 Answers1

2

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.

Lukas Schmid
  • 1,895
  • 1
  • 6
  • 18
  • [Lazy evaluation](https://en.wikipedia.org/wiki/Lazy_evaluation) has a very specific meaning, and Python doesn't have it, so I wouldn't call Python a *lazy* language. – pts Jan 23 '21 at 09:50
  • A more detailed explanation: When *lambda: i+5* is called, *i* is looked up as a variable outside the lambda, and at call time the value is the final value 3. When *lambda x=i: x+5* is defined, the default value of x is set, so *i* is looked up at the time of the definition. – pts Jan 23 '21 at 09:53