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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With