views:

482

answers:

3

In Ruby, I'm used to using Enumerable#inject for going through a list or other structure and coming back with some conclusion about it. For example,

[1,3,5,7].inject(true) {|allOdd, n| allOdd && n % 2 == 1}

to determine if every element in the array is odd. What would be the appropriate way to accomplish the same thing in Python?

+2  A: 

Sounds like reduce in Python or fold(r|l)'?' from Haskell.

reduce(lambda x, y: x and y % == 1, [1, 3, 5])
Deniz Dogan
I've always wondered why catamorphisms are known as "fold"s in **every** functional language but Ruby and Python invent their own names...
ephemient
JavaScript (1.8) uses reduce and I think Clojure uses reduce as well, but I may be mistaken on the latter one... I don't know why this is though.
Deniz Dogan
This is tradition from Common Lisp, which borrowed the name from APL. I think Ruby and Python have much more Lisp influence than from any functional language.
Nathan Sanders
Ah, I'd forgotten about Lisp; I'm far too accustomed to working with the strictly-typed family of functional languages...
ephemient
+13  A: 

To determine if every element is odd, I'd use all()

def is_odd(x): 
    return x%2==1

result = all(is_odd(x) for x in [1,3,5,7])

In general, however, Ruby's inject is most like Python's reduce():

result = reduce(lambda x,y: x and y%2==1, [1,3,5,7], True)

all() is preferred in this case because it will be able to escape the loop once it finds a False-like value, whereas the reduce solution would have to process the entire list to return an answer.

Triptych
+3  A: 

I think you probably want to use all, which is less general than inject. reduce is the Python equivalent of inject, though.

all(n % 2 == 1 for n in [1, 3, 5, 7])
Nathan Sanders