Last modified: Oct 29, 2024 By Alexander Williams

Loop Moves to Next Element in List in Python

When looping through lists in Python, you may want to skip to the next element based on conditions. This guide explains how.

Understanding Loops in Python

Loops allow you to repeat code and process elements within lists. To explore list basics, check out Creating Lists in Python.

Python provides the for loop and while loop to iterate through list items, enabling flexible control over list processing.

Using continue to Skip to the Next Element

The continue statement tells Python to skip the current iteration and move to the next list item.


numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num % 2 == 0:  # Skip even numbers
        continue
    print(num)


1
3
5

In this example, even numbers are skipped, and only odd numbers are printed.

Using enumerate() for Indexed Skipping

Using enumerate(), you can access both the index and value in each iteration, which is helpful for conditional skips.


fruits = ['apple', 'banana', 'cherry', 'date']
for i, fruit in enumerate(fruits):
    if i == 1:  # Skip the second element
        continue
    print(fruit)


apple
cherry
date

The enumerate() function here skips the element with index 1 ("banana").

Using range() to Move to the Next Element

The range() function allows you to control loop indexes, making it easy to skip specific elements or control step size.


numbers = [1, 2, 3, 4, 5]
for i in range(0, len(numbers), 2):  # Step by 2
    print(numbers[i])


1
3
5

Here, the loop skips every other element by using a step of 2 in range().

Using break to Stop Looping

Sometimes, you may want to end the loop if a condition is met, instead of just moving to the next element. The break statement does this.


numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num == 4:
        break  # Stop when reaching 4
    print(num)


1
2
3

Here, the loop stops once it encounters the number 4. To learn more about removing specific items, read Python Remove Item from List.

Looping with List Comprehensions

For shorter code, list comprehensions allow conditional element selection. This is useful when skipping elements that meet certain criteria.


numbers = [1, 2, 3, 4, 5]
odd_numbers = [num for num in numbers if num % 2 != 0]
print(odd_numbers)


[1, 3, 5]

In this example, only odd numbers are selected from the list.

Conclusion

Knowing how to skip elements in a loop lets you create more efficient and flexible code. With Python’s continue, break, and range() features, skipping elements is straightforward.

To further explore list manipulations, read our guide on Python’s Control Flow from the official documentation.