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

Real-Time Road Sign Detection with YOLOv5

# python# machine learning# computer vision# pytorch

If you drive - there's a chance you enjoy cruising down the road. A responsible driver pays attention to the road signs, and adjusts their...

David Landup
David Landup
Details
Project

Data Visualization in Python: The Collatz Conjecture

# python# matplotlib# data visualization

The Collatz Conjecture is a notorious conjecture in mathematics. A conjecture is a conclusion based on existing evidence - however, a conjecture cannot be proven....

David Landup
Jovana Ninkovic
Details

© 2013-2022 Stack Abuse. All rights reserved.

DisclosurePrivacyTerms