Question

I'm trying to use a reduce in Python, but I've found the function I need to call takes 2 parameters.

Is there a way for me to pass one of the parameters in, but not pass the first one?

Like so

b = 10    
reduce(foo, range(20), 0)

def foo(a, b):
     return a + b
Was it helpful?

Solution

You can use lambda to wrap foo:

reduce(lambda a,c: foo(a,b), range(20), 0)

where c will be not used.

OTHER TIPS

In your case you don't need to explicitly pass zero:

print reduce(foo, range(20))

output:

190

Another interpretation of your question is, for the method foo(a, b) you want a to always be 10.
If that is the case, you're not looking for reduce - you're looking for map. And you can achieve the "setting one of the parameters as 'fixed'" behavior by wrapping your foo method

def wrapper(f, a):
    def x(b):
        return f(a, b)
    return x

def foo(a, b):
    return a+b

print map(wrapper(foo, 10), range(11))

output:

[10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top