Iterate Through a List Using While Loop in Python

In Python, we can iterate through a list using a while loop by maintaining an index variable that helps access each element one by one until we reach the end of the list. The loop continues running as long as the index remains within the list’s valid range.


Examples

1. Iterating Through a List Using while Loop

We use a while loop to iterate through a list by maintaining an index variable that increments on each iteration.

</>
Copy
# List of items
fruits = ["apple", "banana", "cherry", "orange"]

# Initialize index
index = 0

# Iterate using while loop
while index < len(fruits):
    print(fruits[index])  # Access and print each element
    index += 1  # Increment index

Explanation:

We define a list called fruits containing multiple elements. The variable index starts at 0. The while loop condition checks if index is less than the list length (len(fruits)). Inside the loop, we print the element at fruits[index] and then increment index by 1, ensuring the next element is accessed in the following iteration.

Output:

apple
banana
cherry
orange

2. Iterating Through a List with Index Values

We can also print both the index and the corresponding element while iterating through the list.

</>
Copy
# List of cities
cities = ["New York", "London", "Paris", "Tokyo"]

# Initialize index
index = 0

# Iterate using while loop
while index < len(cities):
    print(f"Index {index}: {cities[index]}")  # Print index and value
    index += 1  # Increment index

Explanation:

The cities list contains multiple city names. We initialize index at 0 and iterate until it reaches the list length. Inside the loop, we print both the index and the city name in an easy-to-read format, then increment the index by 1.

Output:

Index 0: New York
Index 1: London
Index 2: Paris
Index 3: Tokyo

3. Modifying a List While Iterating

We can use a while loop to modify a list during iteration, such as converting all elements to uppercase.

</>
Copy
# List of colors
colors = ["red", "blue", "green", "yellow"]

# Initialize index
index = 0

# Iterate and modify the list
while index < len(colors):
    colors[index] = colors[index].upper()  # Convert to uppercase
    index += 1

# Print modified list
print("Updated List:", colors)

Explanation:

Here, we define a colors list and iterate using a while loop. Each element is modified by using the .upper() function, converting it to uppercase. After the loop ends, we print the updated list.

Output:

Updated List: ['RED', 'BLUE', 'GREEN', 'YELLOW']

4. Removing Elements from a List While Iterating

We can use a while loop to remove elements that match a certain condition.

</>
Copy
# List of numbers
numbers = [10, 15, 20, 25, 30]

# Initialize index
index = 0

# Iterate and remove numbers greater than 20
while index < len(numbers):
    if numbers[index] > 20:
        numbers.pop(index)  # Remove element
    else:
        index += 1  # Only increment if no removal

# Print modified list
print("Updated List:", numbers)

Explanation:

The numbers list contains multiple integers. We iterate through the list and check if an element is greater than 20. If so, we remove it using pop(). We increment index only when no element is removed to prevent skipping elements.

Output:

Updated List: [10, 15, 20]

Conclusion

Using a while loop to iterate through a list provides flexibility when working with lists dynamically. Following are some key takeaways:

  1. The while loop continues until the index reaches the list length.
  2. We can modify, filter, or remove elements while iterating.
  3. Be cautious when modifying lists during iteration to avoid index skipping.