Skipping Parts of a For Loop

Michael Chermside mcherm at
Mon Sep 16 12:22:13 EDT 2002

> Thomas Guettler wrote:
>>Is there a way to skip some parts in a for loop?
>>   [...]
>>"continue" skipps one element. But how can
>>I skip several?

Andrew Henshaw wrote:
> While not really answering your question... In my opinion, it would be 
> better to use a while loop for that purpose.  The code would be much 
> clearer.

I agree with Andrew. I think the cleanest and most readable way to do it 
would be as follows:

i = 0
while i < UPPER_BOUND:
    if condition:
        i += AMOUNT_TO_SKIP
    i += 1

It makes it very explicit that you are skipping several values of i, and 
any programmer could read this code and understand what it's doing. It 
would be even BETTER if you used a meaningful name for i (perhaps 
"line_number", or "record_id"... use something appropriate to what 
you're doing).

-- Michael Chermside

More information about the Python-list mailing list