0

I am trying to remove all elements in an array that equal a target, a fairly simple procedure. For some reason though, it only removes the first element of the target in the array and I am not sure why. This is my code (python)

arr = [1,2,2,3,4,5,5]
for num in arr:
    if num == 2:
        arr.remove(num)
print(arr)

and it prints the array as [1,2,3,4,5,5]. If any of you know what went wrong that would be great. Thanks

  • 2
    First of all it is very bad to attempt to remove an element from a iterable whilst you are using it to progress through the series. – Frank C. Apr 04 '20 at 08:53
  • 3
    A similar question with a good answer can be found at https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list. It's a bad idea to change a list while iterating over it. – Paul Rene Apr 04 '20 at 08:57
  • Does this answer your question? [Python: Removing list element while iterating over list](https://stackoverflow.com/questions/6022764/python-removing-list-element-while-iterating-over-list) – RoadRunner Apr 04 '20 at 08:57
  • Does this answer your question? [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – user2864740 Apr 04 '20 at 08:59

3 Answers3

1

Your code does not delete all elements because the index of the list reduces by 1 when the 1st element is deleted. And your pointer has already moved ahead.

Instead you can do this:

In [249]: arr = [1,2,2,3,4,5,5] 
In [251]: list(filter(lambda a: a != 2, arr))                                                                                                                                                               
Out[251]: [1, 3, 4, 5, 5]
Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
0

With my comment noted above:

arr = [1,2,2,3,4,5,5]
narr = [x for x in arr if x != 2]
print(narr)
Frank C.
  • 7,758
  • 4
  • 35
  • 45
0

In your code after removing the first occurrence of 2 indexes of elements changed it will now move to point 3 not 2 that's why 2nd occurrence of 2 is not removed.

arr = [1,2,2,3,4,5,5]
i = 0
while arr and i < len(arr):
  if arr[i] == 2:
    arr.remove(arr[i])
    i -= 1
  i += 1
print(arr)
deadshot
  • 8,881
  • 4
  • 20
  • 39