Remove multiple list elements knowing their indices in python

Viewed 72

What is the best and most pythonic way to delete items from a list knowing only the items indices?

my_list = ['zero', 'one', 'two', 'three', 'four']
my_removal_indices = [0, 2, 4]
# what to do
my_list = ['one', 'three']

Please note that something like:

my_list = [item for item in my_list if my_list.index(item) in my_removal_indices]

does not work, as the elements in my_list may not be unique. Also, of course, when just iterating, the indices for my_list change. Is there a nicer way than e.g. creating a new, empty list and storing all wanted items there and setting it as my_list afterwards?

Thanks!

3 Answers

You can use enumerate to iterate through your list, with corresponding indices. Then check those indices against your removal list.

>>> [val for idx, val in enumerate(my_list) if idx not in my_removal_indices]
['one', 'three']

If the index list was long, for performance could also switch to a set to speed up the in check

my_removal_indices = {0, 2, 4}
>>> [val for idx, val in enumerate(my_list) if idx not in my_removal_indices]
['one', 'three']

Try this,

my_list = ['zero', 'one', 'two', 'three', 'four']
my_removal_indices = [0, 2, 4]
print([my_list[i] for i in range(len(my_list)) if i not in my_removal_indices])

If you want to do this in place as opposed to creating a new list with a comprehension, you can mutate the list by deleting the elements so long as you start from the back of the list:

my_list = ['zero', 'one', 'two', 'three', 'four']

my_removal_indices = [0, 2, 4]

for i in sorted(my_removal_indices,reverse=True):
    del my_list[i]

print(my_list)
# ['one', 'three']
Related