Explain Codes LogoExplain Codes Logo

How to remove multiple indexes from a list at the same time?

python
list-comprehension
numpy
performance
Anton ShumikhinbyAnton Shumikhin·Feb 20, 2025
TLDR

To discard items at specific indexes, apply list comprehension as shown:

filtered_list = [item for idx, item in enumerate(lst) if idx not in indexes_to_remove]

filtered_list now omits all items initially at indexes_to_remove in lst.

Removing non-sequential indexes

If your indexes_to_remove aren't sequential, sort them in reverse order before removal with del, like so:

for index in sorted(indexes_to_remove, reverse=True): del lst[index] # We're going in reverse, like a moonwalk! 🕺

This approach ensures correct removal without distorting the indices of subsequent elements.

Tackling large lists: The numpy way

When dealing with large lists, numpy's delete function may be the powerful tool you need:

import numpy as np arr = np.array(lst) filtered_array = np.delete(arr, indexes_to_remove) filtered_list = filtered_array.tolist() # No list is too big for Numpy! 💪

Numpy exhibits superior efficiency with its optimized array operations.

Safe removal with list comprehension

Need to keep the original list intact? Non-destructive filtering with list comprehension has you covered:

indexes_to_remove = set([2, 3, 4, 5]) # O(1) lookups with a set filtered_list = [item for idx, item in enumerate(lst) if idx not in indexes_to_remove] # "Oh dear original list, thou shall not be harmed!" 🛡️

The set enhances the lookup speed, reducing time complexity for vast lists.

Special cases and common hiccups

Simplified removal with slice assignment

Working with continuous indexes? Try slice assignment for a sweet shortcut:

lst[2:6] = [] # Vanished, just like my last pizza slice 🍕

Non-sequential removal simplified

Enumerated list comprehension can filter non-sequential indexes even without resorting to Numpy:

filtered_list = [item for idx, item in enumerate(lst) if idx not in (2, 3, 4, 5)] # Down the list we go, skipping no one but (2, 3, 4, 5) #SkippingAroundTheProblem 🕴️

Limitations of using pop

While pop may seem handy, it's inefficient for bulky operations. The shifting of indexes after each removal makes things painfully slow.

Advanced filtering with list comprehensions

List comprehensions level up with conditional filtering:

filtered_list = [item for item in lst if some_condition(item)]

Not only indexes, but some_condition(item) can also filter based on item properties!