alist = [foo(word) for word in words]
is considered more Pythonic than map alist = map(foo, words) alist = [foo(word) for word in words]
is considered more Pythonic than map alist = map(foo, words)Compare:
alist = [x**2 for x in mylist if x%3==0]
to alist = map(lambda x: x**2,filter(lambda x: x%3==0, mylist)
Plus python also has set comprehension and dict comprehension, which share essentially the same syntax. alist = (map (**2) . filter (\x -> x `mod` 3 == 0)) myList
Or: alist = (map (**2) . filter ((== 0) . (`mod` 3))) myList
If alist is a transformation, and not applied to myList, it's cleaner: alist = map (**2) . filter ((== 0) . (`mod` 3))
Though Haskell also has list comprehensions, with more "mathy" syntax: alist = [x**2 | x <- mylist, x `mod` 3 == 0] alist = [foo(word) for word in words if word.startswith('a')]
alist = map(foo, filter(lambda word: word.startswith('a'), words))
Which reads better?(as it is now, list comprehensions requiring various references to result of a function call evaluate the function each time it's used)
alist = words.filter(lambda word: word.startswith('a')
.map(foo)
That being said, my Python is limited and I don't know it filter/map are available as methods of a list. At the end of the day, there are cases where list comprehensions are much cleaner/understandable... and cases where the reverse is true.They're not. Which is a shame in my opinion, because as you've written it you can clearly read the operations in the order they happen, ie. filter followed by map. Instead, you do have to do the second line of what blossoms wrote above.
And I don't think it's possible to write a list comprehension that reads in execution order, either :(
begins_with_a = lambda x: x.startswith('a')
alist = map(foo, filter(begins_with_a, words)) ;; clojure
(let [begins-with-a #(.startsWith % "a")
foo #(do-some-stuff-with %)]
(-> words (filter begins-with-a) (map foo))))
# ruby
words.filter { |e| e.start_with?(?a) }.map { |e| foo(e) }
It doesn't really make sense for things like `len` and `map` to be global functions in object-oriented languages.the other reason its considered more idiomatic in Python is just because the compiler does a better job of parsing and optimizing list comprehensions.
Where as map could be anything. It could be redefined for all you'd know.
words = ['w1', 'w2', 'w3']
[word[1] for word in words]
['1', '2', '3']
map(lambda x: x[1], words)
['1', '2', '3']
I like looking at the list comprehension better. The use of lambda looks forced in this case. I also imagine there's a penalty for calling the (anonymous) function in map. map(itemgetter(1), words)You cannot index a map object, for example.