Search code examples
pythonfunctional-programmingreducepartial-applicationfunctools

Python: Can I partially apply reduce with an initializer?


The initializer comes after the iterable. This causes problems for partial application. Consider these (trivial) examples:

In [1]: from functools import reduce, partial

In [2]: f = partial(reduce, lambda a,b: a+b, 100)

In [3]: f([1,2,3])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-816cce84b257> in <module>()
----> 1 f([1,2,3])

TypeError: reduce() arg 2 must support iteration

In [4]: f = partial(reduce, lambda a,b: a+b, initializer=100)

In [5]: f([1,2,3])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-816cce84b257> in <module>()
----> 1 f([1,2,3])

TypeError: reduce() takes no keyword arguments

Is there some trick to get around this?


Solution

  • Just change the order of arguments:

    >>> f = partial(lambda func, init, iterable: reduce(func, iterable, init), 
                    lambda a,b: a+b, 100)
    >>> f([1,2,3])
    106