3

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.

Community
  • 1
  • 1
doptimusprime
  • 9,115
  • 6
  • 52
  • 90

1 Answers1

5

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)
301_Moved_Permanently
  • 4,007
  • 14
  • 28