Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting multiple indexes from a list at once - python [duplicate]

My problem is I have a list eg.

lst = [2, 5, 7, 12, 13]


lst.pop(3) #12
lst.pop(4) #13

Because lst[3] has been removed lst[4] is no longer there (out of range). This gives me an error. Now I know you could say change your code to this:...

lst.pop(4) #13
lst.pop(3) #12

...and it ill fix the error, but my problem is my actual code is 'popping' random numbers so it needs to be done all at the same time to avoid error.

Is there any method of 'popping' at the same time?...like something similar to this:

lst.pop(3, 4) #12 and 13 at once

Thanks for any answers.

like image 934
Greg Peckory Avatar asked Jan 09 '14 21:01

Greg Peckory


2 Answers

You can remove them with a list comprehension, which will create a new list:

>>> lst = [2, 5, 7, 12, 13]
>>> [v for i, v in enumerate(lst) if i not in {4,3}]
[2, 5, 7]

You just have to assign this new list to lst again.

like image 78
Maxime Lorant Avatar answered Oct 16 '22 11:10

Maxime Lorant


You can use a list comprehension to rebuild the list:

indices = {3, 4}
newlist = [v for i, v in enumerate(oldlist) if i not in indices]

I used a set for the indices here, as set membership testing is faster than with a list.

Note that a delete (best done with del lst[index]) partially rebuilds the list as well; doing so with one loop in a list comprehension can be more efficient.

Demo:

>>> oldlist = [2, 5, 7, 12, 13]
>>> indices = {3, 4}
>>> [v for i, v in enumerate(oldlist) if i not in indices]
[2, 5, 7]
like image 22
Martijn Pieters Avatar answered Oct 16 '22 09:10

Martijn Pieters