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:
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]
CodePudding user response:
You should iterate through popVal backward and pop the last item first:
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9]
popVal = [0, 5, 8]
for i in popVal[::-1]:
lst.pop(i)
CodePudding user response:
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.