How to Skip Iterations in a Python Loop?

Estimated read time 2 min read

To skip iterations in a Python loop, you can use the continue statement to skip over a specific iteration or range of iterations that you do not want to process in the loop.

Here’s an example of using the continue statement to skip iterations in a Python loop:

# loop through a list and skip a specific element
my_list = ['apple', 'banana', 'cherry', 'date']
for element in my_list:
    if element == 'cherry':
        continue
    print(element)

In this example, we loop through the elements of my_list using a for loop. Inside the loop, we use an if statement to check if the current element is 'cherry'. If the element is 'cherry', we use the continue statement to skip the remaining code in the current iteration and move on to the next iteration. If the element is not 'cherry', we print the element.

The output of this code is:

apple
banana
date

Note that in this example, we use the continue statement to skip the iteration that contains the element 'cherry'. You can modify the condition in the if statement to skip different iterations as needed.

You can also use the range() function to iterate over a range of values and use the continue statement to skip specific iterations. Here’s an example:

# loop through a range of numbers and skip even numbers
for i in range(10):
    if i % 2 == 0:
        continue
    print(i)

In this example, we use the range() function to generate a sequence of integers from 0 to 9, and we loop through the range using a for loop. Inside the loop, we use an if statement to check if the current number i is even (i.e., if the remainder of i divided by 2 is 0). If i is even, we use the continue statement to skip the remaining code in the current iteration and move on to the next iteration. If i is odd, we print the number.

The output of this code is:

1
3
5
7
9

Note that the continue statement can be used in any type of loop in Python, including for loops and while loops.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply