reduce
The reduce
built-in function takes the following arguments:
def reduce(
<list>, # List to reduce
<function>( # Reducing function
acc=<any, mandatory>, # Accumulator
val=<any, mandatory>, # Current value in iterator
idx=<dec, optional>, # Current index, 0=first value
idx_to_end=<dec, optional>, # Current index from end, 0=last value
) -> <any>,
<any>, # Default value
):
And returns the final value of the accumulator after executing over every value in the list.
def red_fn(acc=0, val=0):
return acc + val
return reduce([1,4,7,10], red_fn, 0) # 22
def red_fn(acc='', val='', idx=0, idx_to_end=0):
if idx_to_end == 0:
return acc + val['name'] + ' (' + str(idx+1) + ')'
return acc + val['name'] + ' (' + str(idx+1) + '), '
return reduce([{"name": "John"}, {"name": "Bob"}, {"name": "Charles"}],
red_fn, "") # 'John (1), Bob (2), Charles (3)'