Search code examples
pythoncode-readability

for loop with double condition


I'm looking for a loop construct like for i in list where i < n. I would like to replace this mess:

for i in list:
    if i < n:
        #logic here

Is there something more compact and more elegant?


Solution

  • I'd write it with a guard condition to avoid the layer of indentation.

    for i in list:
        if i >= n: continue
    

    A one-liner is this:

    for i in (k for k in list if k < n):
        ...
    

    But I think the obvious code with the if inside the loop is much easier to understand.