Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Delete elements in range in Python
Deleting elements from a Python list by specific indices requires careful handling to avoid index shifting issues. This article explores two effective approaches to delete multiple elements based on their index positions.
Using sorted() with del Statement
The most straightforward approach is to sort the indices in reverse order and delete elements from highest to lowest index. This prevents index shifting issues ?
Example
numbers = [11, 6, 8, 3, 2]
# The indices to delete
indices_to_delete = [1, 3, 0]
# printing the original list
print("Given list is :", numbers)
print("The indices list is :", indices_to_delete)
# Delete elements using sorted indices in reverse order
for i in sorted(indices_to_delete, reverse=True):
del numbers[i]
# Print result
print("List after deleted elements :", numbers)
Given list is : [11, 6, 8, 3, 2] The indices list is : [1, 3, 0] List after deleted elements : [8, 2]
How it works: The indices [1, 3, 0] are sorted in reverse order to [3, 1, 0]. Deleting from highest index first prevents the remaining indices from becoming invalid due to list shrinkage.
Using List Comprehension with enumerate
This approach creates a new list containing only elements whose indices are not in the deletion list ?
Example
numbers = [11, 6, 8, 3, 2]
# The indices to delete
indices_to_delete = [1, 3, 0]
print("Given list is :", numbers)
print("The indices list is :", indices_to_delete)
# Create new list excluding specified indices
numbers[:] = [value for index, value in enumerate(numbers)
if index not in indices_to_delete]
print("List after deleted elements :", numbers)
Given list is : [11, 6, 8, 3, 2] The indices list is : [1, 3, 0] List after deleted elements : [8, 2]
How it works: The list comprehension iterates through the original list with enumerate(), keeping only elements whose index is not in the deletion list.
Comparison
| Method | Performance | Memory Usage | Best For |
|---|---|---|---|
sorted() + del |
O(n log n) | Low | In-place deletion |
| List comprehension | O(n) | Higher | Functional approach |
Conclusion
Use sorted() with del for memory-efficient in-place deletion. Use list comprehension for a more readable functional approach when memory is not a constraint.
