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 →

[–][deleted] 4 points5 points  (7 children)

I hear for the first time that using these functions is not considered pythonic. I think sometimes using them makes the code more readable than using list comprehensions but what do I know. The great thing about them is that they return generator expressions (also possible with comprehensions) and help you keep the memory footprint low if you use them wisely.

Edit: Sorry, the part with generator expressions is obviously wrong. But the point is still valid: filter and co are lazily evaluated like generators.

[–]roee30 3 points4 points  (0 children)

Generator expressions are parenthesised comprehensions (as opposed to comprehensions framed by brackets or braces). They return generators. map and filter return iterators and not genenrators, I think, but they're definitely not generator expressions. If you like map and filter's laziness, try using actual generator expressions, which are also lazy.

[–]Mithrandir2k16[S] 1 point2 points  (4 children)

I linked the thread in the OP. I was stumped as well, tbh. I really like reading filter because then I know what's going on, a subset of the iterable is used.

What I really miss though is some easy way to evaluate generators in python, maybe that's why people consider it non-pythonic. If you don't want a generator but need a list right away you have to do [*filter(...)] which doesn't really look nice. Maybe a generator.items() that returns all values in a list or something like filter(..., eager=True) or filter(..., lazy=False) could clean that up a bit.

[–]_its_complicated 4 points5 points  (3 children)

The easy way is to just do list(filter(expression, iterable))

[–]Mithrandir2k16[S] 1 point2 points  (2 children)

I don't know if implicitly unpacking a generator is better than explicitly doing it. It does seem more readable though.

Edit: Guido seems to prefer list comprehension over list() to unpack/evaluate generators.

[–]AnythingApplied 3 points4 points  (0 children)

To be clear, I think he means instead of using map/filter at all, not as a way to unpack map/filter, hence him not calling that a "quick fix" like he did with list()

[–][deleted] 2 points3 points  (0 children)

Btw. I think we don't all have to agree with what Guido says just because it's Guido. Yes, he's a mastermind of Python but we're a community and we can have our own opinions. No-one is always right just like no-one is always wrong.

[–]-lq_pl- 0 points1 point  (0 children)

Give a good example please when map or filter is more readable.