1

I was playing around with lists and functions on python and was trying to create a list of functions using a loop as following:

n = 5
fun = []

for i in range(n):
    def f(x):
        return x + i
    fun.append(f)

I tried to test the list using prints as following

for s in range(n):
    print(fun[s](1))

I expected to obtain 1 2 3 4 5 but instead got 5 5 5 5 5. When using the variable i

for i in range(n):
    print(fun[i](1))

I obtained what I was expecting, however the all functions inside the list 'fun' behave like x + 4. I was wondering what is causing this issue and what can be done to fix it. Thank you.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
TERA
  • 11
  • 2
  • Although the duplicate is about lambda functions, the principal is the same: they're both variable scope in functions. Lambda functions and `def` functions don't make any difference here. – iBug Dec 08 '18 at 08:33
  • 2
    Short answer: use `def f(x, i=i)` to capture the value of `i` **at the definition of `f`**. This way different functions in the list capture different values. – iBug Dec 08 '18 at 08:34
  • 1
    You may find [this article](https://docs.python-guide.org/writing/gotchas/#late-binding-closures) useful as well. – bereal Dec 08 '18 at 08:35

0 Answers0