I've been given a list of integers called nums
, and am trying to remove all occurrences of the value (val
). I'm trying to see where val
matches an index of nums
and am trying to remove it from the list. However, I keep getting a "list index out of range" error. I'm guessing it is because as I am popping the element of nums
that matches val
, it shrinks the list so it goes out of range. Is it not possible to remove all occurrences of value in this way?
nums = [3,2,2,3]
val = 2
for i in range(len(nums)):
if val == nums[i]:
nums.pop(i)
print(nums)