1

How can I write the following code so that not all functions are the same?

>>> def g(x):
...     l = []
...     for i in range(1,10):
...         def f(x):
...             return x + i
...         l.append(f)
...     return l

The idea should be that g returns a list of 9 functions where the first function returns x+1 the second x+2 etc. However, since in python everything is an object all previous function definition will be overwritten. How can I solve this?

math
  • 1,868
  • 4
  • 26
  • 60
  • I think problem here is the `i` being the final value, not the function. – hurturk Jun 29 '17 at 12:56
  • All your functions are identical: they all add the current value of `i`. And when you call the functions, the current value of `i` will be 10. – khelwood Jun 29 '17 at 12:58

1 Answers1

3

This does not overwrite the functions in the final list

def make_f(x, i):
    def f():
        return x + i
    return f


def g(x):
    l = []
    for i in range(1, 10):
        l.append(make_f(x, i))
    return l

for f in g(10):
    print f()

11
12
13
14
15
16
17
18
19
Ghilas BELHADJ
  • 13,412
  • 10
  • 59
  • 99