Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalent to Ruby Array.each method

Tags:

In Python what is equivalent to Ruby's Array.each method? Does Python have a nice and short closure/lambda syntax for it?

[1,2,3].each do |x|
  puts x
end
like image 436
BuddyJoe Avatar asked Sep 23 '13 22:09

BuddyJoe


2 Answers

Does Python have a nice and short closure/lambda syntax for it?

Yes, but you don't want it in this case.

The closest equivalent to that Ruby code is:

new_values = map(print, [1, 2, 3])

That looks pretty nice when you already have a function lying around, like print. When you just have some arbitrary expression and you want to use it in map, you need to create a function out of it with a def or a lambda, like this:

new_values = map(lambda x: print(x), [1, 2, 3])

That's the ugliness you apparently want to avoid. And Python has a nice way to avoid it: comprehensions:

new_values = [print(x) for x in values]

However, in this case, you're just trying to execute some statement for each value, not accumulate the new values for each value. So, while this will work (you'll get back a list of None values), it's definitely not idiomatic.

In this case, the right thing to do is to write it explicitly—no closures, no functions, no comprehensions, just a loop:

for x in values:
    print x
like image 70
abarnert Avatar answered Sep 19 '22 04:09

abarnert


The most idiomatic:

for x in [1,2,3]:
    print x
like image 45
Shashank Avatar answered Sep 20 '22 04:09

Shashank