Nicer way to write folding? (list reversal?)

Jason Orendorff jason at jorendorff.com
Wed Jan 2 17:57:21 EST 2002


> In the code below, foldr2 is clearly uglier than the rest.  Is there a
> nicer way (without destructive reversal - yuck - of the list
> argument)?  Also, are these things built-in (can't find them)?

foldr() is built-in.  It's called reduce().

  >>> from operator import add
  >>> nums = [1, 2, 3, 4, 5]
  >>> reduce(add, nums, 0)
  15

## Jason Orendorff    http://www.jorendorff.com/




More information about the Python-list mailing list