[Python-ideas] if-statement in for-loop
Chris Angelico
rosuav at gmail.com
Sun Sep 11 08:10:47 EDT 2016
On Sun, Sep 11, 2016 at 9:59 PM, Paul Moore <p.f.moore at gmail.com> wrote:
> # Hacky use of a generator expression:
> for i in (x for x in range(10) if x != 5):
> body()
This is what I'd like to compare the proposal against. It's perfectly
legal but pretty ugly - why should you nest two 'for' loops just for
the sake of filtering?
> # Functional style
> for i in filter(range(10), lambda n: n != 5):
> body()
And this one is very close (I'd use i instead of n in the lambda
function), but still fairly verbose.
That said, though, filtered iteration isn't common enough to demand
its own syntax IMO. I do it fairly often, but it's usually fine to
just have a condition on a separate line. (I do use ": continue"
rather than making it two lines.)
ChrisA
More information about the Python-ideas
mailing list