4 ms·
> I think dropping filter() and map() is pretty uncontroversial; filter(P, S) is almost always written clearer as [x for x in S if P(x)] Performance reasons as
by malvosenior 8y ago
> I think dropping filter() and map() is pretty uncontroversial; filter(P, S) is almost always written clearer as [x for x in S if P(x)]
Performance reasons aside, I strongly disagree with this statement. Anyone can see that `filter` is going to apply the predicate to the iteratable in the first statement. The second statement is super awkward, declares a temp var `x` which to my limited Pythonic eyes looks like it's just calling the identity function on `x` that comes back from the "filter".
Again, I have no doubt Python is optimized to perform better with the second form, but that seems a limitation in the interpreter. The syntax to non-Python devs is pretty raunchy imho.
- Tarean 8y agoI am used to haskell's syntax, does this become more readable once you get used to it? The haskell equivalent would be [x | x <- s, p x]
- roenxi 8y agoIn many senses this is a style thing, but: There is going to be a pretty sharp break between people who accept that working with a collection deserves special syntax support and those who don't. The readability issue for me isn't that the syntax doesn't look nice, it is that I've invested years into making a very efficient little mental space that deals with "data2 = fn(data1)" style constructs and I want to use it here like I do everywhere else. Some silly-high percentage of for loops can be cast into this data2 = fn(data1). Why am I being told that it isn't readable? If this isn't easy to read, then something is wrong with the function syntax. A chaining operator, to recast fn3(fn2(fn1(data))) => data > fn1 > fn2 > fn3 with reduce is much more readable, debuggable and easy to reason about than having to remember what syntax todays language uses to talk about collections and how that works in to the flow of data in my program.
- goto11 8y agoI agree with you for the example with a named function P, but as Guido points out, filter predicates are typically simple expression which you don't want to create a named function for. So it would be say `filter(lambda x: x < 17, S)` versus `[x for x in S if x < 17]`. I think the second one is nicer even if the repeated x is ugly. Neither is great though. The comprehension syntax assumes filters are accompanied by maps. A filter without a map is a somewhat ugly special-case. The real issue is the lack of a lambda syntax with a pythonic feel.
- pseudalopex 8y agoThe list comprehension syntax is just set notation with Python keywords instead of symbols. Haskell, JavaScript, and Julia have similar syntax. It's also similar to the equivalent loop. Which of these is clearer? [x * y for x in S if P(x) > 0] map(lambda x: x * y, filter(lambda x: P(x) > 0, S))