2

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)
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
Bashaar Shah
  • 35
  • 1
  • 3

2 Answers2

3

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]
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
  • I should have mentioned that im sort of starting python to do leetcode and was trying to solve the remove all occurrences of a target number from the array in-place, but I thought I was on to something here. – Bashaar Shah Feb 16 '22 at 04:04
0

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]
Udesh
  • 2,415
  • 2
  • 22
  • 32