How to Skip the First Loop on a For Loop in Python?

Estimated read time 2 min read

To skip the first iteration of a for loop in Python, you can use the continue statement inside the loop. The continue statement causes the loop to immediately jump to the next iteration, skipping any remaining code in the current iteration.

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

# loop through a list and print all elements except the first one
my_list = ['apple', 'banana', 'cherry', 'date']
for i in range(len(my_list)):
    if i == 0:
        continue
    print(my_list[i])

In this example, we loop through the elements of my_list using a for loop and the range() function. Inside the loop, we use an if statement to check if the current index i is equal to 0 (i.e., the first iteration of the loop). If i is equal to 0, we use the continue statement to skip the remaining code in the current iteration and jump to the next iteration. If i is not equal to 0, we print the element of my_list at index i.

The output of this code is:

banana
cherry
date

Note that in this example, we use the range() function to generate a sequence of integers from 0 to the length of my_list minus 1, which serves as the index values for the loop. Alternatively, you can loop directly over the elements of my_list using a forin loop, like this:

# loop through a list and print all elements except the first one
my_list = ['apple', 'banana', 'cherry', 'date']
for element in my_list[1:]:
    print(element)

In this example, we use slicing to create a new list that starts from the second element of my_list and iterates over it using a forin loop. The output of this code is the same as before:

banana
cherry
date

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply