Enumerating in Python for the Rubyist

While there are similarities between Python and Ruby that make the transition from one to the other not a particularly difficult one, there are also some vexing differences — lack of enumerables in Python being one.

This is, of course, not a comprehensive list Python equivalents for all of Ruby’s enumerables, but some of my more frequently used. In Python, it typically comes down to list comprehension, which can be very elegant, though there are some built-in functions.

words = ["hello", "goodbye", "foo", "bar"]
words.each do |word|
    puts word
end
words = ["hello", "goodbye", "foo", "bar"]
for word in words:
    print word
words = ["hello", "goodbye", "foo", "bar"]
lengths = words.map do |word|
    word.length
end
lengths #=> [5, 7, 3, 3]
words = ["hello", "goodbye", "foo", "bar"]
lengths = [len(word) for word in words]
lengths #=> [5, 7, 3, 3]
words = ["hello", "goodbye", "foo", "bar"]
words.select do |word|
    word.length > 3
end
words #=> ["hello", "goodbye"]
words = ["hello", "goodbye", "foo", "bar"]
filter(lambda word: len(word) > 3, words) #=> ["hello", "goodbye"]

Or, with list comprehension:

words = ["hello", "goodbye", "foo", "bar"]
[word for word in words if len(word) > 3]
words = ["hello", "goodbye", "foo", "bar"]
words.any? do |word|
    word.length > 3
end #=> true
any(len(word) > 4 for word in words) #=> True
words = ["hello", "goodbye", "foo", "bar"]
words.inject(0) do |sum, word|
    sum + word.length
end #=> 18
words = ["hello", "goodbye", "foo", "bar"]
reduce(lambda sum, word: sum + len(word), words, 0) #=> 18