How to remove items from a list while iterating?

It is generally not recommended to remove items from a list while iterating over it because it can cause unexpected behavior. Instead, you can create a new list that contains only the items you want to keep, or you can use a for loop with a range of indices to iterate over the list and remove items by index. Another option is to use a list comprehension or generator expression to filter out unwanted items.

Watch a course Python - The Practical Guide

Here's an example of creating a new list:

original_list = [1, 2, 3, 4, 5]
new_list = [i for i in original_list if i % 2 == 0]
print(new_list)  # [2, 4]

Here's an example of using a range of indices to remove items:

original_list = [1, 2, 3, 4, 5]
for i in range(len(original_list) - 1, -1, -1):
    if original_list[i] % 2 != 0:
        original_list.pop(i)
print(original_list)  # [2, 4]

It is important to note that in python version 3.3 and later, for-loops in python internally make an iterator out of the input. So in python 3.3 and later, the following will raise a RuntimeError: dictionary changed size during iteration.

for i in original_list:
    if i%2 !=0:
        original_list.remove(i)

You can use a list comprehension or generator expression to remove the unwanted items as shown above.