-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
  • 52,918
  • 14
  • 115
  • 123
YaronGh
  • 371
  • 2
  • 4
  • 13

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
  • 105,104
  • 32
  • 201
  • 196
2

Use list comprehension filtering :

 [ my_list[i] for i in range(len(my_list)) if i not in to_delete ] 
Graham
  • 7,431
  • 18
  • 59
  • 84
Ohad Eytan
  • 8,114
  • 1
  • 22
  • 31