4 ms·
List comprehensions are more flexible and easier to read in the non-trivial case. Sure in the trivial case you show a map might be considered neater, but just
by dagw 12y ago
List comprehensions are more flexible and easier to read in the non-trivial case. Sure in the trivial case you show a map might be considered neater, but just adding a filter is enough to make the list comprehension more readable in my mind. Python's lambda syntax also makes using maps and filters quite ugly.
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.
- column 12y agohi, you are lacking a closing parenthesis in your second example.
- Peaker 12y agoIn Haskell, the latter looks like: 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]
- zo1 12y agoDon't forget generator comprehensions which are almost identical to list comprehensions. But instead of evaluating the whole result set and returning it, they return a generator that you can then iterate over. Very neat stuff.