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:
1 2 3 4 |
for i in range(5): if i == 2: continue print(i) |
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.
1 2 3 4 5 6 |
fruits = ['apple', 'banana', 'orange', 'grape', 'strawberry'] for fruit in fruits: if fruit == 'orange': continue print(fruit) |
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.
1 2 3 4 5 6 |
animal_weights = {'cat': 5, 'dog': 30, 'elephant': 5000, 'giraffe': 1200} for animal, weight in animal_weights.items(): if weight < 1000: continue print(animal, weight) |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# Lists and Tuples fruits = ['apple', 'banana', 'orange', 'grape', 'strawberry'] for fruit in fruits: if fruit == 'orange': continue print(fruit) print("\n") # Dictionaries animal_weights = {'cat': 5, 'dog': 30, 'elephant': 5000, 'giraffe': 1200} for animal, weight in animal_weights.items(): if weight < 1000: continue print(animal, weight) |
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.