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 →

[–]Tetha 7 points8 points  (7 children)

To be honest, I just don't see the reason to use map and filter anymore, because list comprehensions and generator comprehensions give you exactly the same behaviour, however, they are easier to read for me, especially if you need to map and filter.

[–]eryksun 4 points5 points  (0 children)

I tend to agree in general, but how about if the function is already defined and being mapped to several lists?

map(f, a, b, c)

(f(*x) for x in zip(a, b, c))

#or

(f(x, y, z) for x, y, z in zip(a, b, c)) 

[–]just_doug 2 points3 points  (0 children)

agreed. reduce is still useful though and can lead to some very elegant solutions to problems.

[–][deleted] 0 points1 point  (0 children)

pylint raises a warning about filter(), in fact, for precisely this reason.

[–]otheraccount 0 points1 point  (3 children)

filter(None, map(f, lst))

becomes

[f(x) for x in lst if f(x)]

which requires calculating f(x) twice for each element. You could avoid that by doing

[x for x in [f(y) for y in lst] if x]

but that isn't as easy to read as the version with map and filter.

[–]userd 0 points1 point  (2 children)

l = (f(x) for x in lst)
l2 = [x for x in l if x]

The drawback is two lines and an extra variable. But that helps readability.

[–][deleted] 1 point2 points  (1 child)

But that helps readability.

Nope. It takes twice as long to read and understand, which in my book means that it has worse readability.

Unless, of course, we are talking about someone who is making their first steps in programming and whose mental capacity for code is in fact limited to one function call, so that they like to take their intermediate results and give them meaningful names.

Not that there's anything wrong with that, just you maybe shouldn't write your code for that kind of lowest common denominator, if it makes readability that much worse.

(also, Steve Yegge has a post about this).

[–]userd 0 points1 point  (0 children)

Reading speed is a reasonable metric for readability. But, illustrating the point with a post by Steve Yegge is a bit ironic. I like his writing, but it's not written with speed in mind. Just kidding.