←back to thread

317 points est | 1 comments | | HN request time: 0.2s | source
Show context
BerislavLopac ◴[] No.17448998[source]
I would like to see adding a comprehension-like filtering clause to for-statements:

    for n in range(100) if n%2:
        print(f'{n} is odd number')
Does anyone know if there is a PEP covering that?
replies(5): >>17449022 #>>17449029 #>>17449035 #>>17449036 #>>17452328 #
theSage ◴[] No.17449029[source]
Agreed these are a little verbose but they get the job done no?

    for n in filter(is_even, range(100)):
        print(f'{n} is odd number')

    for n in (i for i in range(100) if i % 2 == 0):
        print(f'{n} is odd number')
Are there any points against these solutions other than verbosity?
replies(1): >>17452040 #
1. BerislavLopac ◴[] No.17452040[source]
Yes, that's what I've been using so far, especially filter, which works quite well with lambda. But if you have a separate function anyway it's better to make it into a generator:

    def odd_range(count):
        return (x for x in range(count) if x%2)
        
    for n in odd_range(100):
        ...
As for the second one, I'm just not too happy with the implied two loops (even if it amounts to only one in practice).