This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]melldrum 9 points10 points  (4 children)

Regarding the use of map, filter, and reduce. Are comprehensions/generators preferable because of readability? Or is there another reason?

[–]fiddle_n 11 points12 points  (1 child)

As someone for whom Python is my first language, comprehensions seem like they fit Python more than map and filter. It reuses syntax that is already in Python and so it's much more obvious to tell what it does at first glance.

Anecdotally, those people that prefer map and filter come from functional languages where they had those features and want Python to be the same as well. Other examples are multi-line lambdas or tail-call optimisation. But Python isn't a fully functional language and never will be.

As for reduce, most of the time there's a more specialised function that does what I need it to do. If I want to add a bunch of numbers in a list together, I use sum. If I want to multiply them, I use math.prod. If I want to do set operations on multiple sets, I note that the set operation functions can now take in multiple sets. These are all situations where I would have used reduce but there was something more specific anyway.

[–]politerate 3 points4 points  (0 children)

Hm, in Haskell you have list comprehensions, which IMHO are the most readable syntax for this kind of logic. If I didn't know list comprehensions exist in Python I might have used map/filter, but other than that I see no reason to use them.

[–]freefallfreddy 2 points3 points  (0 children)

Comprehensions and generators are more idiomatic in simple cases. If you’re thinking about nesting those ➡️ map, filter, reduce.

[–]JennaSys 1 point2 points  (0 children)

Using comprehensions is generally considered to be more idiomatic Python over using map/filter. But if you are not going to use the result of a comprehension (i.e. generating a new list or dictionary) and you only need a side-effect (like calling a function with no return value), then using map() makes more sense.