Python

Python

Python - Looping Through Lists

One of the key concepts that both beginners and advanced developers encounter is working with loops to process lists. Let’s dive into how to use loops, explore examples, common mistakes, and helpful tips in detail.


Loops are constructs that allow you to perform repetitive actions. When working with lists, loops help you process each element—whether it’s printing them, modifying data, or performing calculations.

In Python, two types of loops are most commonly used with lists:

  • for — iterating over elements.
  • while — looping with a condition.

The for Loop with Lists

The for loop is the most convenient and widely used method for processing lists in Python. It allows you to iterate directly over elements or use their indices.

Direct Element Iteration

If you simply want to go through all the elements in a list, use this syntax:

Output:

apple
banana
pear

👣 Explanation:

  • fruit is a temporary variable that takes on the value of each list element in turn.
  • in fruits specifies that we’re iterating over the fruits list.

This approach is perfect when you don’t need the element’s index, just the data itself.

Iteration with Indices Using range() and len()

If you need to know an element’s position (index) in the list, you can combine range() with len():

Output:

Item 0: apple
Item 1: banana
Item 2: pear

👣 Explanation:

  • len(fruits) returns the length of the list (3 in this case).
  • range(3) generates a sequence of numbers from 0 to 2.
  • fruits[i] accesses an element by its index.

Using enumerate()

A more "Pythonic" (natural for Python) way to get both the index and element at the same time is the enumerate() function:

Output:

Item 0: apple
Item 1: banana
Item 2: pear

👣 Explanation:

  • enumerate(fruits) returns pairs of (index, element).
  • You can set a starting index, e.g., enumerate(fruits, start=1).

This method is preferred because it’s more readable and concise.

The while Loop with Lists

The while loop is less common for lists but useful when you need manual control over iteration or when the list’s length changes during processing.

📌 Example:

Output:

apple
banana
pear

👣 Explanation:

  • i is a counter that increases by 1 (i += 1) after each iteration.
  • The condition i < len(fruits) ensures we don’t go beyond the list’s bounds.

When to Use while?

  • When you want to remove elements from the list during iteration.
  • When you need to skip elements based on complex conditions.

📌 Example with Removal:

Useful Loop Operators

Python provides several operators to simplify working with loops:

  1. break — exits the loop.
  2. continue — skips the current iteration and moves to the next one.
  3. else — runs if the loop completes without being interrupted.

📌 Example with break:

Output:

apple

👣 Explanation:

  • The for loop iterates over the fruits list one by one: first "apple," then "banana," then "pear."
  • Condition: Checks if the current element equals "banana."
  • The break operator: As soon as the condition is met (at "banana"), the loop stops immediately, and further iterations (e.g., "pear") are skipped.
  • Why only "apple" is printed? The print(fruit) statement comes before break, so "apple" gets printed, but the loop stops before printing "banana."

When to use? break is handy when you need to stop the loop as soon as a specific condition is met.

📌 Example with continue:

Output:

apple
pear

👣 Explanation:

  • The for loop iterates over the fruits list one by one.
  • Condition: Checks if the current element is "banana."
  • The continue operator: When the condition is true (at "banana"), continue skips the rest of the current iteration and moves to the next element ("pear"), bypassing the print(fruit) statement for "banana."
  • Why isn’t "banana" printed? Because continue triggers before print, skipping that iteration.
  • Why are "apple" and "pear" printed? For those elements, the condition isn’t met, so continue doesn’t trigger, and print(fruit) executes normally.

When to use? continue is useful when you want to skip specific elements but keep the loop running.

📌 Example with else:

Output:

No orange found.

👣 Explanation:

  • The for loop iterates over the fruits list, checking each element against "orange."
  • Condition: Looks for "orange" in the list.
  • The break operator: If "orange" were found, the loop would stop, and the else block would be skipped.
  • The else block: In Python, the else block in loops runs only if the loop completes naturally—i.e., it iterates fully without being interrupted by break.
  • Why "No orange found"? Since "orange" isn’t in the list, the condition never triggers, break doesn’t run, and the else block executes after the loop finishes.

When to use? else is great for checking whether a loop was interrupted or completed fully, such as when searching for an item.

Summary:

  • break — stops the loop when a goal is reached.
  • continue — skips individual iterations without stopping the loop.
  • else — runs an action if the loop finishes without interruptions.

Try tweaking the conditions or lists in these examples to get a better feel for how they work!

Common Mistakes When Working with Loops and Lists

  1. Modifying a List During a for Loop: Adding or removing elements from a list during a for loop can lead to errors or skipped elements. Use a while loop or create a list copy instead:
  1. Going Out of Bounds in a while Loop: Forgetting to increment the counter i can cause an infinite loop or an IndexError.

  2. Inefficient Index Handling: Instead of manually calculating indices, use enumerate() for cleaner code.

Practical Examples

1. Summing List Elements

This classic example shows how to use a for loop to process list elements and accumulate a result (here, a sum). The total variable acts as an "accumulator" that grows with each iteration.

👣 Explanation:

  • numbers = [1, 2, 3, 4, 5]: Creates a list numbers with five integers: 1, 2, 3, 4, and 5—our data to work with.
  • total = 0: Initializes the total variable to 0 as a starting point for the sum.
  • for num in numbers:: The for loop iterates over each element in numbers one by one.
  • num: A temporary variable that takes the value of each element in turn: first 1, then 2, up to 5.
  • total += num: Adds the current element’s value to total on each iteration (+= is shorthand for total = total + num).
  • After the last iteration, total equals 15—the sum of all elements.

Python also offers the built-in sum(numbers) function for a shorter solution:

However, the loop version is great for learning the logic and for cases where you need additional actions within iterations.

Try replacing += with *= to calculate the product instead:

This example is a fantastic starting point for experimenting with loops and lists!

2. Filtering a List

This code demonstrates how to use a for loop to filter data from one list and build a new list based on a condition.

👣 Explanation:

  • numbers = [1, 2, 3, 4, 5]: Creates the source list numbers with five integers—our data to filter.
  • even_numbers = []: Initializes an empty list even_numbers to store even numbers found during the loop.
  • for num in numbers:: Iterates over each element in numbers one by one.
  • num: Temporary variable holding the current element’s value.
  • if num % 2 == 0: Checks if the current element num is even.
    • The % operator (modulus) returns the remainder of dividing num by 2.
    • If the remainder is 0 (num % 2 == 0), the number is even (e.g., 2, 4).
    • If it’s 1, the number is odd (e.g., 1, 3, 5).
  • even_numbers.append(num): If the condition holds (the number is even), adds num to even_numbers using the .append() method.

Python also supports list comprehensions for a shorter approach, but the loop with .append() is clearer for beginners and allows more complex logic inside.

3. Modifying Elements

This code shows how to use a for loop with indices to modify list elements in place, altering the original list fruits rather than creating a new one.

👣 Explanation:

  • fruits = ["apple", "banana", "pear"]: Creates a list fruits with three strings—our data to modify.
  • for i in range(len(fruits)):: Iterates over the indices of the fruits list.
  • len(fruits) returns 3 (the list has three items).
  • range(3) generates the sequence 0, 1, 2—indices for "apple" (0), "banana" (1), and "pear" (2).
  • i: Temporary variable taking each index value: 0, then 1, then 2.
  • fruits[i] = fruits[i].upper(): Replaces the element at index i with its uppercase version.
  • .upper(): A string method that converts all characters to uppercase (e.g., "apple".upper() becomes "APPLE").

How to Iterate Over a List in Reverse

Method 1. Using reversed()

The reversed() function returns an iterator that goes through the list from end to start.

Output:

pear
banana
apple

👣 Explanation:

  • reversed(fruits) creates an iterator starting from the last element ("pear") and moving to the first ("apple").
  • The for loop iterates over the elements in the order provided by the iterator.
  • The original fruits list remains unchanged.

Method 2. Using range() with a Negative Step

You can use range() with a step of -1 to iterate over indices from last to first.

Output:

pear
banana
apple

👣 Explanation:

  • len(fruits) is 3, so len(fruits) - 1 = 2—the index of the last element ("pear").
  • range(2, -1, -1) generates the sequence 2, 1, 0:
    • First argument (2): Starting index.
    • Second argument (-1): Stopping index (exclusive).
    • Third argument (-1): Step, moving backward.
  • fruits[i] accesses the element at each index: fruits[2] = "pear", fruits[1] = "banana", fruits[0] = "apple".

Method 3. Using while with a Decreasing Counter

A while loop lets you manually control the index, moving from end to start.

Output:

pear
banana
apple

👣 Explanation:

  • i = len(fruits) - 1 sets the starting index to the last element (2 for "pear").
  • while i >= 0: Continues as long as the index is 0 or greater.
  • fruits[i] prints the element at the current index.
  • i -= 1 decreases the index by 1 each iteration: 2 → 1 → 0.

When to use: When you need flexibility, such as for removing elements or complex conditions.

Method 4. Using a Slice [::-1]

A list slice with a step of -1 creates a reversed list to iterate over.

Output:

pear
banana
apple

👣 Explanation:

  • fruits[::-1] is a slice where:
    • Empty start (:): From the beginning.
    • Empty end (:): To the end.
    • Step -1: Move backward.
  • Creates a new list ["pear", "banana", "apple"] that the for loop iterates over.

If you want to modify elements in reverse order, here’s an example:

Tips

  1. For Beginners:

    • Start with the simple for item in list loop.
    • Don’t forget the colon at the end of the for loop line.
    • Feel free to experiment with examples.
    • Use print() for debugging and understanding what’s happening.
  2. For Intermediate Learners:

    • Master enumerate() for cleaner code.
    • Learn list comprehensions as an alternative to loops.
    • Use built-in functions like sum(), map(), or filter() for optimization.
  3. General Advice:

    • Document your code with comments.
    • Test edge cases (empty lists, single-element lists).
    • Leverage built-in functions and methods like sum(), len(), max(), and min() to simplify and optimize your code.

Conclusion

Working with lists using loops is a fundamental skill that paves the way for tackling more complex programming challenges. The for loop is ideal for straightforward iterations, while offers flexibility and control, and tools like enumerate() and list comprehensions make your code more elegant and efficient. Practice, experiment, and soon you’ll handle any list in Python with confidence!

Frequently Asked Questions About List Iteration

What Happens If I Add or Remove Elements While Iterating Over a List?

Removing elements during direct iteration (for item in list) shifts indices, which can cause Python to skip elements or raise an error.

Solution: Use a while loop or iterate over a copy of the list:

How Do I Stop a Loop Early?

The break operator exits the loop immediately:

What Is enumerate() and Why Use It?

The enumerate() function lets you iterate over a list with both indices and elements, offering cleaner code than range(len()):

It’s handy when you need both the index and value at the same time.

Subscribe to our newsletter

Get the freshest news and resources for developers, designers and digital creators in your inbox each week

© 2000 – 2025 SitePoint Pty. Ltd.
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.