0

Le't assume I have a list with elements, from which I want to remove a few rows on the basis of a list of row indexes. This is an example:

l = ['ciao','hopefully','we','are','going','to','sort','this','out']
idx = [1,3,5]

If I do the following, it doesn't work as the loop doesn't consider that the lenght of the list after the nth remove object is n-i:

for x in idx:
            del l[x]

# what happens? The code only removes correctly the first element of idx, then it doesn't take into account that the list has shrunk and therefore the nth index no longer corresponds to the updated row list.

Note, I cannot turn the list into an array and then use np.delete as my list is coming from webscraping and it fails when I try to do so.

Can anyone suggest me a way to remove list's elements on the basis of its rows in one shot without messing up with the shifting of the index?

Thanks!

Rollo99
  • 1,601
  • 7
  • 15

3 Answers3

1

You can use list comprehension and enumerate.

# enumerate give:
# :    0   ,   1       ,  2 ,  3  ,  4    , 5  ,  6   , 7    ,  8
l = ['ciao','hopefully','we','are','going','to','sort','this','out']
idx = set([1,3,5])
out = [el for i, el in enumerate(l) if not i in idx]
print(out)

['ciao', 'we', 'going', 'sort', 'this', 'out']
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
1

Another approach without enumerate

new_l = [item for item in l if l.index(item) not in idx]
David Meu
  • 1,527
  • 9
  • 14
1

If you must delete them in place:

>>> lst = ['ciao', 'hopefully', 'we', 'are', 'going', 'to', 'sort', 'this', 'out']
>>> idx = [1, 3, 5]
>>> for i in sorted(idx, reverse=True):
...     del lst[i]
...
>>> lst
['ciao', 'we', 'going', 'sort', 'this', 'out']

If do not need, you can use list comprehension to create a new list:

>>> lst = ['ciao', 'hopefully', 'we', 'are', 'going', 'to', 'sort', 'this', 'out']
>>> idx = [1, 3, 5]
>>> idx_set = set(idx)
>>> [v for i, v in enumerate(lst) if i not in idx_set]
['ciao', 'we', 'going', 'sort', 'this', 'out']

Of course, you can also achieve the effect of deleting in place through slice assignment:

>>> lst[:] = [v for i, v in enumerate(lst) if i not in idx_set]
Mechanic Pig
  • 6,756
  • 3
  • 10
  • 31