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.

.each

words = ["hello", "goodbye", "foo", "bar"]words.each do |word|
puts word
end
words = ["hello", "goodbye", "foo", "bar"]for word in words:
print word

.map

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]

.filter/.select

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]

.any

words = ["hello", "goodbye", "foo", "bar"]words.any? do |word|
word.length > 3
end #=> true
any(len(word) > 4 for word in words) #=> True

.inject/.reduce

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

Senior Software Engineer | www.adriennedomingus.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store