Delete elements in range in Python


Deleting a single element from a python is straight forward by using the index of the element and the del function. But there may be scenarios when we need to delete elements for a group of indices. This article explores the approaches to delete only those elements form the list which are specified in the index list.

Using sort and del

In this approach we create a list containing the index values where deletion has to happen. The we sort and reverse them to preserve the original order of the elements of the list. Finally we apply the del function to the original given list for those specific index points.

Example

 Live Demo

Alist = [11,6, 8, 3, 2]

# The indices list
idx_list = [1, 3, 0]

# printing the original list
print("Given list is : ", Alist)

# printing the indices list
print("The indices list is : ", idx_list)

# Use del and sorted()
for i in sorted(idx_list, reverse=True):
del Alist[i]

# Print result
print("List after deleted elements : " ,Alist)

Output

Running the above code gives us the following result −

Given list is : [11, 6, 8, 3, 2]
The indices list is : [1, 3, 0]
List after deleted elements : [8, 2]

idx_list after sorting and reverse becomes [0,1,3]. So only the elements from these positions get deleted.

Using enumerate and not in

We can also approach the above program by using enumerate and a not in clause inside a for loop. The result is same as above.

Example

 Live Demo

Alist = [11,6, 8, 3, 2]

# The indices list
idx_list = [1, 3, 0]

# printing the original list
print("Given list is : ", Alist)

# printing the indices list
print("The indices list is : ", idx_list)

# Use slicing and not in
Alist[:] = [ j for i, j in enumerate(Alist)
if i not in idx_list ]

# Print result
print("List after deleted elements : " ,Alist)

Output

Running the above code gives us the following result −

Given list is : [11, 6, 8, 3, 2]
The indices list is : [1, 3, 0]
List after deleted elements : [8, 2]

Updated on: 04-May-2020

651 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements