1

I am trying to remove a specific value from an array.Here is the code:

nums = [0,1,2,2,3,0,2,4]
val = 2

for i in nums:

    if i ==val:
        nums.remove(i)
print(nums)

Here im expecting an answer of [0, 1, 3, 0, 4] but getting [0, 1, 3, 0, 2, 4]. Why the last '2' still exists? whats im missing here?

  • Does this answer your question? [Remove all occurrences of a value from a list?](https://stackoverflow.com/questions/1157106/remove-all-occurrences-of-a-value-from-a-list) – xerx593 Feb 18 '21 at 16:19

2 Answers2

1

You can try using while statement, where you loop until the value you want to remove is totally gone. Here's the code:

nums = [0,1,2,2,3,0,2,4]
val = 2
while val in nums:
    nums.remove(val)
print(nums)
Lucy
  • 35
  • 7
  • An answer should explain what it changes and why. How does `while` help here? It might not be as obvious to the OP as it is to you and me. – underscore_d Feb 18 '21 at 16:50
  • My bad! Well, we're using while loop to iterate our condition. "while val in nums:" if the val which is 2, is still inside our array, the loop will still go and the condition nums.remove(val) will be executed where we remove val inside nums. Then after the while removing the val in the array, it will print the values of our array. – Lucy Feb 18 '21 at 17:01
1

A few things to remember here:

  • When you use the code for i in nums: the i is the actual value not the index
  • .remove(i) is going to remove by value, which is fine
  • .remove(i) will remove only the first instance

The problem you are running into is because you're iterating the list and removing items at the same time. There are many ways to work around this, but a really simple method to get this working is effectively making a copy of the list in the iteration.

You can do this by changing your iteration to for i in list(nums):

and your final outcome will be the [0, 1, 3, 0, 4] that you're expecting.

Also note that in the original code, when you think it's found and is removing the final 2, it's actually removing the second 2 which is why you are left with the 2 at the end.

Hopefully that helps to clarify things a bit

Steve Shay
  • 116
  • 4