-1

I am trying to identify how we can pass in the default arguments that have been defined for a function when it is used in map

For example for the following snippet:

def func1(a,x=3,y=2):
    return (a + x)*y
lst = [1,2,3]
print map(func1,lst)

Is there a way to override the values for x & y so that for each element of lst x=4 and y=3 without using lambda or list comprehension?

2
  • You can write another function and use that instead. Commented Dec 4, 2018 at 13:18
  • or you can use lambda and keep the x, y as variables. Commented Dec 4, 2018 at 13:20

1 Answer 1

0

One way to achieve this (not mentioned in the duplicate target, and slightly less relevant there) is to use a nested function, where the outer function sets the values and returns the inner function, which is what is then executed in the map:

def func1(x=3,y=2):
    def inner(a):
        return (a + x)*y
    return inner

lst = [1, 2, 3]
print map(func1(), lst)
print map(func1(x=4, y=3), lst)

Note the added () even if you don't want to overwrite the default arguments, otherwise it will apply the outer function to every element of lst.

The outer function is basically a function factory that produces inner functions with correctly set parameters.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.