Python: How To Remove Items From a List While Iterating

Iterating over a list of objects in Python to access and change them is a common thing to do while coding. This specific situation occurs when you try to remove items from a list while iterating over it. That way, you are effectively changing the length of the list while accessing its elements, therefore risking facing unexpected behavior.

Warning: Generally speaking, removing elements from a list while iterating over it in Python is not a great idea and good practice advises against it. This Byte was published for those who would, knowing this, like to proceed with the operation. Some like living life dangerously!

Let's proceed by assuming you need to remove elements from a list using the in-place semantics. Say you have a list of integers and you want to remove all odd numbers:

numbers = list(range(1, 25))
# [1, 2, 3, 4, ..., 24]

Removing all of the odd numbers from a list is equal to leaving all even numbers in the list - that's the approach we'll be taking. Let's, therefore, create a method that checks whether the passed number is even and return True if it is:

Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

def even(num):
    if num % 2 == 0:
        return True
    return False

Now we can utilize the even() method to remove all odd numbers from the numbers list while iterating over it:

numbers[:] = [n for n in numbers if even(n)]

This will alter the numbers list so it now contains only even numbers:

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24]

Advice: To solve the problem of removing elements from a list while iterating, we've used two key concepts - list comprehension and slice notation. If you want to gain more comprehensive overview of those concepts, you can read our "List Comprehensions in Python" and "Python: Slice Notation on List" guides.

Last Updated: April 13th, 2023
Was this helpful?

Ā© 2013-2024 Stack Abuse. All rights reserved.