Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

In Python3, you are really looking at...

    (func(a) for a in collection)
    map(func, collection)
as equivalent. If you want a list (and not a generator), you would need to do this:

    [func(a) for a in collection]
    list(map(func, collection))
For me, the first set (comprehensions) of notation has a more mathematical feel to it, i.e. { x^2 | x \in 0...10 }. Just replace the bar with "for" and it's almost the same thing.

I believe the documentation for `filter` even mentions that it is equivalent to the comprehension[1].

[1] https://docs.python.org/3/library/functions.html#filter



I've always found the list comprehension harder to read for non trivial examples. It may just be a matter of which a person learned first.


> It may just be a matter of which a person learned first.

I think this is the case, for me map is much harder to read. But I also think that comprehensions go back to math sets, so I was familiar with this even before learning any programming. Therefore comprehensions clicked immediately for me and it's by far my favourite python feature.


I learned both around the same time, but even in good functional languages like Haskell, using a comprehension for anything more than simple problems results in an unreadable mess.

map or filter are much easier to read for complex data manipulations and as a bonus, their composition rules make it easy to increase performance. For example, if you see two map functions together, you can wrap them in a compose and only map over your elements once. This isn't as immediately obvious when you're using comprehensions.


Could you give an example?

Do you mean something like

> [ manager.name for manager in set([ person.manager for person in employees ])]

?

I assume with something like set() or unique() you need to create the intermediate iterable anyway, but without it I have trouble finding an example where doing a single list comprehension wouldn't suffice.


Not quite. I learned map and filter much earlier, and still I use more list comprehensions, both in Python and in Erlang.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: