YaronGh YaronGh - 4 months ago 9
Python Question

How to delete elements from a list using a list of indexes?

If I have the following list of elements:

list = ['one', 'two', 'three', 'four']


and I have another list that contains the indexes I need to delete from the list above:

to_delete = [0,2]


How can I delete those elements from
list
using
to_delete
? Using a
for
loop doesn't work since, obviously, when you delete one element from a list the index of each remaining element changes.

What can I do?

Answer

You can use enumerate together with a conditional list comprehension to generate a new list containing every element of my_list that is not in the index location from to_delete.

my_list = ['one', 'two', 'three', 'four']
to_delete = [0,2]

new_list = [val for n, val in enumerate(my_list) if n not in to_delete]

>>> new_list
['two', 'four']
Comments