1

I am working in Python 2.7 and need to generate a list of functions each of which has a different default argument but where the functions are explained. This is not the best explanation, but I think the example below clarifies my question. Is there a way of doing this?

function_list = []
for i in range(10):
    function_list.append(lambda x: myfunc(i,x))

def myfunc(a,b):
    print a + b

This doesn't work, as, in this example, all functions in the function list return 9 + x

In the example above "x" is a separate variable to be passed to the function in a different way.

I realise that this is a pretty ugly construction but have inherited a large amount of code around this that would need to be changed to avoid this.

0

1 Answer 1

3

You can use i as a default value for a lambda with two arguments. This way it will fit better to the question description:

need to generate a list of functions each of which has a different default argument

for the following code:

function_list = []
for i in range(10):
    function_list.append(lambda x, y=i: myfunc(x,y))

for f in function_list:
    f(5)

The output will be:

5
6
7
8
9
10
11
12
13
14

also you can use f with two arguments:

for j,f in enumerate(function_list):
    f(j+2,5)

and you'll get:

7
8
9
10
11
12
13
14
15
16
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.