3 ms·
It's a matter of comfort. I was doing imperative programming for years, and more functional now. You've got for loops, list comprehensions, newer dict compreh
by the-alchemist 3y ago
It's a matter of comfort.
I was doing imperative programming for years, and more functional now.
You've got for loops, list comprehensions, newer dict comprehensions, map/filter, generators, etc. in Python.
Python programmers tend to prefer for loops and comprehensions. List comprehensions, especially, dict comprehensions being much newer.
Living mostly in the pre-Java 8 Java world, I used for loops as much as the next guy, like the rest of the Java world. But I really liked list comprehensions. And then Java got streams and map and filter, etc., and wow, I loved it. Even most Java programmers started embracing the new "functional" paradigms.
Now that I've been both (and its more powerful cousins in Clojure), I'd say map/filter are "more readable". It depends on the implementation too: try merging two dictionaries in Python, ugh [1] [2]. Awkward any way you slice it. Watch out what version of Python 3.x you have! Watch the order of arguments, and some variations modify in-place! You're also never sure if your result will be a list or a dict.
Try map'ing a dict in Python: don't, it's not worth it [3]. These things are actually pretty easy, even in Java, let alone Clojure.
For the record, Clojure has map/filter and list comprehensions (called for comprehensions, and they're even more powerful than Python because they can terminate early [0]).
So, yes, in Python, map/filter can often be a pain. They were afterthoughts, and less readable than the alternatives. For languages with powerful map/filter and friends, these functional equivalents are much more flexible and readable. And it appears that most people that are familiar with both prefer the functional variety.
[0]: https://clojuredocs.org/clojure.core/for https://clojuredocs.org/clojure.core/for
[1]: https://stackoverflow.com/questions/38987/how-do-i-merge-two-dictionaries-in-a-single-expression-in-python https://stackoverflow.com/questions/38987/how-do-i-merge-two...
[2]: https://gist.github.com/SZanlongo/bc4baa90d3795db7c6ed7e8d4150f1de https://gist.github.com/SZanlongo/bc4baa90d3795db7c6ed7e8d41...
[3]: https://stackoverflow.com/questions/23862406/filter-items-in-a-python-dictionary-where-keys-contain-a-specific-string https://stackoverflow.com/questions/23862406/filter-items-in...