Python: How To Remove Items From a List While Iterating

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 opration. 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 form a list while iterating, we've used two key concepts - list comprehesion 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: July 21st, 2022
Was this helpful?
Project

Building Your First Convolutional Neural Network With Keras

# python# artificial intelligence# machine learning# tensorflow

Most resources start with pristine datasets, start at importing and finish at validation. There's much more to know. Why was a class predicted? Where was...

David Landup
David Landup
Details
Course

Data Visualization in Python with Matplotlib and Pandas

# python# pandas# matplotlib

Data Visualization in Python with Matplotlib and Pandas is a course designed to take absolute beginners to Pandas and Matplotlib, with basic Python knowledge, and...

David Landup
David Landup
Details

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

DisclosurePrivacyTerms