←back to thread

317 points est | 2 comments | | HN request time: 0.419s | 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 #
keedon ◴[] No.17449036[source]

  for n in [i for i in range(100) if i%2 == 0]:
    print n
Will work (if a bit repetitive looking)
replies(1): >>17449104 #
1. BerislavLopac ◴[] No.17449104[source]
It's not just repetitive; this particular example actually creates a list before starting the external loop -- imagine it with range(100000000) or something. It is better if you replace [] with (), which creates a generator.
replies(1): >>17449881 #
2. Herald_MJ ◴[] No.17449881[source]
`range()` also takes an optional `step` argument which would help here.