How To Skip Element In the For Loop in Python

In this tutorial, we will learn how to skip elements in a for loop in Python. Sometimes, you may want to skip some elements while iterating through a list, tuple, or dictionary using a for loop. This can be easily done using the continue statement in Python.

Step 1: Understanding the Continue Statement

The continue statement is used to skip the current iteration of a loop and continue with the next iteration. When the continue statement is encountered, Python ignores the remaining code in the current iteration and moves to the next iteration of the loop.

Here is a simple example of using the continue statement in a for loop:

Output:

0
1
3
4

As you can see, the continue statement skips the iteration when the value of i is 2 and continues with the next iteration.

Step 2: Skipping Elements in Lists and Tuples

Now, let’s see how to skip elements when iterating through a list or a tuple.

Output:

apple
banana
grape
strawberry

The above code skips ‘orange’ and prints the rest of the fruits in the list.

Step 3: Skipping Key-Value Pairs in Dictionaries

Similarly, you can use the continue statement to skip key-value pairs while iterating through a dictionary.

Output:

elephant 5000
giraffe 1200

In this example, we skipped animals with weights less than 1000 and printed only the animals with weights greater than or equal to 1000.

Full Example Code

Output:

apple
banana
grape
strawberry

elephant 5000
giraffe 1200

Conclusion

Skipping elements in a for loop in Python is easy using the continue statement. It allows you to skip specific items or conditions, making your code more flexible and efficient. Remember to use the continue statement judiciously to avoid making your code less readable or more difficult to debug.