-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?

1 Answers1

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.

Graipher
  • 6,891
  • 27
  • 47