Python | Remove items from a list while iterating

Remove items from a list while iterating in Python

Many times, it maybe happened that you are trying to process through a list and you don’t want some elements to be part of it. The one-stop solution is to note down those unwanted elements and remove them in the next iteration. Let’s see how we can remove items from a list while iterating in Python.

We have a list, let’s say [1,2,3,4,5,6,7,8,9,10]. I want to remove prime numbers from this list. How can I do that?

Look at the function for prime number first:

import math
def is_prime(n):
    if n<=1:
        return 0
   
    limit = math.floor(math.sqrt(n))
    for i in range(2,limit+1):
        if(n%i==0):
            return 0
    return 1

We will use the above code later in the article.

1. Using Loop to Remove items from a list

The very basic and naive solution is to use a for loop or while loop and use conditional statements to remove the elements using remove() method from the list.

The no-brainer code for this purpose might be:

import math
def is_prime(n):
    if n<=1:
        return 0
   
    limit = math.floor(math.sqrt(n))
    for i in range(2,limit+1):
        if(n%i==0):
            return 0
    return 1
    
numbers = [1,2,3,4,5,6,7,8,9,10]

for element in numbers:
    if(is_prime(element)):
        numbers.remove(element)

print(numbers)

Output:

[1, 3, 4, 6, 8, 9, 10]

Well, you have included ‘3’ to be removed from the list, but why can we still see it?
This is because remove() changes the indexing of the elements whenever it performs deletion. The for loop here will iterate over each index exactly once, hence the unexpected results.

How do we fix this? Simple. Just iterate over the copy of the list and delete elements from the original list.

numbers = [1,2,3,4,5,6,7,8,9,10]

for element in list(numbers):
    if(is_prime(element)):
        numbers.remove(element)

print(numbers)

Output:

[1, 4, 6, 8, 9, 10]

2. Using List comprehension to remove items from a list

We can also use list comprehension to remove items from a list while iterating as list comprehension gives a concise and precise way to work over lists through a single-line code.

import math
def is_prime(n):
    if n<=1:
        return 0
   
    limit = math.floor(math.sqrt(n))
    for i in range(2,limit+1):
        if(n%i==0):
            return 0
    return 1
    
numbers = [1,2,3,4,5,6,7,8,9,10]

updated_list = [element for element in numbers if is_prime(element)==0]
print(updated_list)

Output:

[1, 4, 6, 8, 9, 10]

3. Backward traversing

Remember the problem we faced with the remove() method? Well, there’s another way to fix it. It is by using the del keyword and traversing backward so there will be no change in indexing.

import math
def is_prime(n):
    if n<=1:
        return 0
   
    limit = math.floor(math.sqrt(n))
    for i in range(2,limit+1):
        if(n%i==0):
            return 0
    return 1
    
numbers = [1,2,3,4,5,6,7,8,9,10]

for i in range(len(numbers)-1,-1,-1):
    if(is_prime(numbers[i])):
        del numbers[i]

print(numbers)

Output:

[1, 4, 6, 8, 9, 10]

4. filter()

We can use the filter() method to remove items from a list while iterating as the filter() function returns an iterator where the items of a sequence are filtered through a function that determines whether to accept them or not.

As the filter() returns an iterator, it is important to typecast them to the sequence.

import math
def is_prime(n):
    if n<=1:
        return 0
   
    limit = math.floor(math.sqrt(n))
    for i in range(2,limit+1):
        if(n%i==0):
            return 0
    return 1
    
numbers = [1,2,3,4,5,6,7,8,9,10]

updated_list = list(filter(lambda x:not is_prime(x),numbers))
print(updated_list)

Output:

[1, 4, 6, 8, 9, 10]

Note: The ‘not’ keyword used here includes the false elements in the resultant lists, i.e. composite numbers here. If the ‘not’ keyword is removed, the resultant list will be of prime numbers as the is_prime() return True if the number is prime.

5. Append elements to a new list

This is again a no-brainer or quick approach to remove the items in one go.

Instead of removing or deleting items from the list, just include the wanted elements in the new list and use that new list throughout the program.

import math

def is_prime(n):
    if n<=1:
        return 0
   
    limit = math.floor(math.sqrt(n))
    for i in range(2,limit+1):
        if(n%i==0):
            return 0
    return 1
    
numbers = [1,2,3,4,5,6,7,8,9,10]
updated_list = []

for item in numbers:
    if(is_prime(item)==False):
        updated_list.append(item)
        
print(updated_list)

Output:

[1, 4, 6, 8, 9, 10]

Hurray! The work is done.

Those were the few ways to remove items from the list while traversing only once. Libraries like functools, itertools, numpy also provide some powerful methods. But these were the most frequent and easier-to-use methods. Hope this helps!

Thank you for visiting our website.


Also Read:

Share:

Author: Ayush Purawr