Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove multiple list elements knowing their indices in python

Tags:

python

list

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!

like image 202
MD98 Avatar asked Mar 25 '26 04:03

MD98


1 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']
like image 122
Cory Kramer Avatar answered Mar 27 '26 17:03

Cory Kramer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!