Home > Software engineering >  How delete a element of a list and save the original index of deleted element?
How delete a element of a list and save the original index of deleted element?

Time:08-26

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.

CodePudding user response:

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.

CodePudding user response:

You can also leverage enumerate

for index, val in enumerate(List):
  if val == value:
    List.remove(val)
    break

print(index)

CodePudding user response:

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')
  • Related