-2

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?

Holger Just
  • 49,152
  • 14
  • 106
  • 117
YaronGh
  • 341
  • 2
  • 3
  • 12

2 Answers2

4

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']
Alexander
  • 96,739
  • 27
  • 183
  • 184
2

Use list comprehension filtering :

 [ my_list[i] for i in range(len(my_list)) if i not in to_delete ] 
Graham
  • 7,035
  • 17
  • 57
  • 82
Ohad Eytan
  • 7,319
  • 1
  • 20
  • 30