how to return multiple variations of function in python

Question:

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?

Asked By: math

||

Answers:

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
Answered By: Ghilas BELHADJ
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.