Wednesday, November 3, 2010

List comprehension ruby vs python

Been exploring a bit of list comprehension in Python so today I thought I peeked over the fence to see a bit of what is happening at ruby's end..

I really like how they are doing their list comprehension over there, check this example out:

[1,2,3,4,5].select(&:even?).map(|x| x*3)

That is almost readable code even in English! I would read it as something like this.."From the list 1,2,3,4,5 select even numbers and map it to number times 3". Really nice!

This vs the clunkier Python code ...

[x*3 for x in [1,2,3,4,5] if x%2 == 0]

I mean it both works just that it seems more elegant in ruby. Would be nice if we had that even or odd function in Python. Yeah I know it's trivial to write ... but then following that logic wouldn't it also be trivial to include it in the standard library. Probably my way of emulating this example ain't exactly the best and there are other more succint ways of doing it, if so be great to drop me a line here, but for now hang on while I peek over the fence more :)
Post a Comment