Open In App

Python - Delete elements in range

Last Updated : 26 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, we often need to remove elements from a list within a specific range. This can be useful when cleaning data or modifying lists based on certain conditions.

Using List Comprehension

List comprehension is one of the most Pythonic and efficient ways to filter out elements. It is concise, easy to understand, and runs in a single pass over the list. This method checks each element in the list and only keeps those that do not fall within the range 5 to 10.

Python
a = [1, 3, 5, 7, 9, 11, 13]

# Remove elements between 5 and 10 
a = [x for x in a if not (5 <= x <= 10)]

print(a) 

Output
[1, 3, 11, 13]

Other methods to remove elements from a list within a specific range in Python are:

Using del Statement with Slicing

The del statement can be used to delete a range of elements by specifying their indices. This method is efficient when we know the indices of the elements we want to remove. In this code, we use slicing to specify the range of indices to remove. The elements at indices 2, 3, and 4 are removed.

Python
a = [1, 3, 5, 7, 9, 11, 13]

# Delete elements between index 2 and 4 (inclusive)
del a[2:5]

print(a)  

Output
[1, 3, 11, 13]

Using filter() with Lambda Function

filter() function provides a way to remove elements from a list based on a condition. The filter() function filters elements based on the condition provided in the lambda function. We convert the result back into a list to update the variable a.

Python
a = [1, 3, 5, 7, 9, 11, 13]

# Remove elements between 5 and 10 (inclusive) 
a = list(filter(lambda x: not (5 <= x <= 10), a))

print(a)  

Output
[1, 3, 11, 13]

Using pop()

pop() method removes elements at a specific index. We can use it in a loop to remove elements that fall within a certain range. However, this method is less efficient than the previous ones, especially for large lists, because pop() causes the list to shift every time an element is removed.

Python
a = [1, 3, 5, 7, 9, 11, 13]

# Remove elements between 5 and 10 
i = 0

while i < len(a):
    if 5 <= a[i] <= 10:
        a.pop(i)
    else:
        i += 1

print(a)  

Output
[1, 3, 11, 13]

Using remove()

remove() method removes the first occurrence of a specified value. If we want to delete elements in a range, we can loop through the list and call remove() on each element that falls within the range. This is a relatively inefficient method, especially when there are many elements to remove, because it searches for each element in the list.

Python
a = [1, 3, 5, 7, 9, 11, 13]

# Remove elements between 5 and 10 
for item in a[:]:
    if 5 <= item <= 10:
        a.remove(item)

print(a)  

Output
[1, 3, 11, 13]

Next Article

Similar Reads