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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With