Remove list elements in a for loop in Python

avatar

Borislav Hadzhiev

Last updated: Aug 15, 2022

banner

Photo from Unsplash

Remove list elements in a for loop in Python #

To remove list elements in a for loop:

  1. Use a for loop to iterate over a copy of the list.
  2. Check if each item meets a condition.
  3. Use the list.remove() method to remove the items that meet the condition.
main.py
my_list = [22, 33, 66, 77, 99] for item in my_list.copy(): if item < 50: my_list.remove(item) print(my_list) # 👉️ [66, 77, 99]

We used the list.copy() method to get a copy of the list.

main.py
my_list = [22, 33, 66, 77, 99] print(my_list.copy()) # 👉️ [22, 33, 66, 77, 99]

The list.copy method returns a shallow copy of the object on which the method was called.

This is necessary because we aren't allowed to remove items from a list while iterating over it.

However, we can iterate over a copy of the list and remove items from the original list.

main.py
my_list = [22, 33, 66, 77, 99] for item in my_list.copy(): if item < 50: my_list.remove(item) print(my_list) # 👉️ [66, 77, 99]

On each iteration in the for loop, we check if the current item is less than 50 and remove the elements that meet the condition.

You might also see examples that use the my_list[:] syntax to get a shallow copy of the list by using list slicing.

main.py
my_list = [22, 33, 66, 77, 99] for item in my_list[:]: if item < 50: my_list.remove(item) print(my_list) # 👉️ [66, 77, 99]

We used the my_list[:] syntax to get a slice that represents the entire list.

main.py
my_list = [22, 33, 66, 77, 99] print(my_list[:]) # 👉️ [22, 33, 66, 77, 99]
This approach achieves the same result as using the list.copy() method, it creates a shallow copy of the list that we can iterate over.

In general, the list.copy() method is a little more readable than using a slice that represents the entire list.

Here is another example.

main.py
my_list = [None, 22, 33, None, 66, 77, None, 99] for item in my_list.copy(): if item is None: my_list.remove(item) print(my_list) # 👉️ [22, 33, 66, 77, 99]

We used a for loop to remove all None values from a list while iterating over it.

The most important thing to note when removing items from a list in a for loop is to use the list.copy() method to iterate over a copy of the list.

If you try to iterate over the original list and remove items from it, you might run into difficult to locate bugs.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.