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

Question:

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

Asked By: Christopher Rae

||

Answers:

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)
Answered By: Javier Martín

Python reduce function is removed from global namespace to functools and general instruction is to use list comprehension instead. Using list-comprehensions I would do it like this:

arr = [1,2,3,4,5,6,7,8]
max_index = 5
# 0-based index
print( sum([val for index, val in enumerate(arr,0) if index<=max_index]) )
# output is 21
Answered By: Robert Lujo
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.