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?
To determine if every element is odd, I’d use
all()In general, however, Ruby’s
injectis most like Python’sreduce():all()is preferred in this case because it will be able to escape the loop once it finds aFalse-like value, whereas thereducesolution would have to process the entire list to return an answer.