Search code examples
pythonreducefunctools

is there anyway of getting a values index in an iterable when using functools.reduce in python


I have a function that would benefit from using functools.reduce it would act something like this

import functools

def add(total, val, max_index, index):
    if index > max_index:
        return total
    else:
        return total + val

arr = [1,2,3,4,5,6,7,8]
functools.reduce(functools.partial(add, max_index=5), arr, 0)

how do I pass the index of the val in the arr into the function or is it just not possible I thought about using a global variable to track the index but of course would much rather not

by the way my function is meant to be used for an array a lot larger than an array of len 8


Solution

  • You could always pass enumerate(arr) which transforms any iterable of elements X_i into another of elements (i,X_i).

    Then the function would need to unpack the "value" it received (which is now a 2-tuple) into index and value.

    Example:

    import functools
    
    def add(total, index_val, max_index):
        index, val = index_val
        if index > max_index:
            return total
        else:
            return total + val
    
    arr = [1,2,3,4,5,6,7,8]
    res = functools.reduce(functools.partial(add, max_index=5), enumerate(arr,0), 0)
    print(res)