How delete a element of a list and save the original index of deleted element?

Question:

I want delete some elements of one list equal to a value:
I can do it :

List =[1,2,3.....]
List = [x for x in List if x != 2]

How can i save the indexs of the deleted elements ?

I want to use this index to delete elements of another list.

Asked By: Vitor Bento

||

Answers:

Simplest solution is to make a list of indices to keep, then use that to strip the elements from both of your lists. itertools provides a handy compress utility to apply the indices to keep quickly:

from itertools import compress

tokeep = [x != 2 for x in List]
List = list(compress(List, tokeep))
otherlist = list(compress(otherlist, tokeep))

Alternatively (and frankly more clearly) you can just use one loop to strip both inputs; listcomps are fun, but sometimes they’re not the way to go.

newlist = []
newotherlist = []
for x, y in zip(List, otherlist):
    if x != 2:
        newlist.append(x)
        newotherlist.append(y)

which gets the same effect in a single pass. Even if it does feel less overtly clever, it’s very clear, which is a good thing; brevity for the sake of brevity that creates complexity is not a win.


And now, to contradict that last paragraph, the amusingly overtly clever and brief solution to one-line this:

List, otherlist = map(list, zip(*[(x, y) for x, y in zip(List, otherlist) if x != 2]))

For the love of sanity, please don’t actually use this, I just had to write it for funsies.

Answered By: ShadowRanger

Based on documentation

list_first = ['d', 'a']
list_second = ['x', 'z']
def remove_from_lists(element):
  index_deleted = list_first.index(element)
  list_first.remove(element)
  list_second.pop(index_deleted)
remove_from_lists('d')
Answered By: KosztDojscia

You can also leverage enumerate

for index, val in enumerate(List):
  if val == value:
    del List[index]
    break

print(index)
Answered By: Abhishek Kumar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.