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!
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With