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)
CodePudding user response:
You should not try to remove elements from the list as you're iterating over it, as the memory is shifting as you're accessing it.
Instead, you should create a new list:
nums = [3,2,2,3]
val = 2
print([num for num in nums if val != num]) # Prints [3, 3]
CodePudding user response:
use remove
method to remove vlaues from list
nums = [3,2,2,3]
val = 2
l = list(nums)#creating new list
for v in l:
if v == val:
nums.remove(val)#removing values
print(nums)
output:
$ python3 file.py
[3, 3]