Skip to content
Advertisement

How to remove multiple object from the list at the same time

w = [1, 2, 3, -3, -2, 4, -4, 1, 2, -2]


def data_remover(xarray, ind):
    for i in ind:
        del xarray[i]
    return xarray


print(data_remover(w, [2, 3, 5, 6, 8, 9]))

I am trying to write a code such that it removes adjacent (+n, -n) pairs such as (3,-3) (4,-4) etc.

However I cannot use del[i] since when I remove an element the xarray also changes. I tried to use deepcopy to copy the x array but I couldnt manage to run the code.

from copy import deepcopy

w = [1, 2, 3, -3, -2, 4, -4, 1, 2, -2]


def data_remover(xarray, ind):
    xcopy = deepcopy(xarray)
    for i in ind:
        del xarray[i]
    return xarray


print(data_remover(w, [2, 3]))

Advertisement

Answer

You can sort the list of indices in descending order so that deleting an element will not effect the position of another. You can do this by reversed(ind)

w = [1, 2, 3, -3, -2, 4, -4, 1, 2, -2] 
def data_remover(xarray, ind):
    for i in reversed(ind):
         del xarray[i] 
    return xarray 
print(data_remover(w, [2, 3, 5, 6, 8, 9]))

Or if your indices are not in any order you can always sort them in descending order.

for i in sorted(ind, reverse = True):
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement