Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I add a skip condition to a for loop without slowing it down?

I am writing a function which processes a big list of elements, and want to add the functionality that certain elements are skipped depending on an input argument. Here’s what the code looks like:

def f(lst, skipsEnabled=False):
    for elem in lst:
        if skipsEnabled and skipCheck(elem):
            continue
        else:
            # do stuff to elem here

When skipsEnabled is false, the if skipsEnabled conditional can be ignored every time, however it still gets checked on every iteration and it slows my loop down. I could put the conditional before the loop, but then I’d need to duplicate the loop and this is not very OOPy since all the elem processing code would be copy-pasted in both loops.

Is there a clean way to do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Define a method to do the element processing code and then have the loop with or without the conditional and then call the same method for the processing.

It is highly unlikely that you are actually generating a large efficiency saving here, though. The skipsEnabled and skipCheck(elem) will short circuit and never call skipCheck() so it’s a single boolean check that always branches the same way. That will optimise well.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading