Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pop many items from list?

I want to pop certain items from my list. This is my code:

lst = [1,2,3,4,5,6,7,8,9]
popVal = [0, 5, 8]
for i in popVal:
    lst.pop(i)

The expected output should be [2,3,4,5,7,8] as index 0, 5 and 8 are removed from lst

However, I get a error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
IndexError: pop index out of range

And if I print my list, this is the output

[2, 3, 4, 5, 6, 8, 9]

>Solution :

Each time you pop an element, the list shrinks. As such, what used to be at index 8 for example, is now at index 3.

Assuming your list of popVal is strictly ascending, the following modified code would work

lst = [1,2,3,4,5,6,7,8,9]
popVal = [0, 5, 8]
for n, i in enumerate(popVal):
    lst.pop(i - n)

This ensures that as the list shrinks, the index to pop from shrinks accordingly as well.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading