Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python reduce accum as an argument

Tags:

python

reduce

As per this thread in SO, reduce is equivalent to fold. However, in Haskell, accum parameter is also passed to fold. What is the way in python to pass accumulator in reduce.

my_func(accum, list_elem):
     if list_elem > 5:
       return accum and True # or just accum
     return accum and False # or just False

reduce(my_func, my_list)

Here, I want to pass True as accumulator. What is the way in python to pass initial accumulator value.

like image 536
doptimusprime Avatar asked Jul 21 '26 18:07

doptimusprime


1 Answers

As per the documentation, reduce accepts an optional third parameter as the accumulation initializer.

You can write:

def my_func(acc, elem):
    return acc and elem > 5

reduce(my_func, my_list, True)

or, using a lambda:

reduce(lambda a,e: a and e > 5, my_list, True)

Alternatively, for this particular example, where you want to check that 5 is strictly lower than all the elements in my_list, you can use

greater_than_five = (5).__lt__
all(greater_than_five, my_list)
like image 86
301_Moved_Permanently Avatar answered Jul 24 '26 08:07

301_Moved_Permanently



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!