0

i am using this code and i want to remove all the 2's from the array arr . but when i am running it is returning me [2,2,2,"string"]

 arr = [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,"string"]

 for i in arr:
   if i == 2:
     arr.remove(i)

 print(arr)

2 Answers2

0

The general rule of thumb is: Don't try to mutate the list you are iterating. Check this question :)

If you want to modify the list while iterating it. You may try this:

arr = [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,"string"]

for i in arr[:]:
    if i == 2:
        arr.remove(i)

With list comprehension, we can make this better and more pythonic:

arr = [element for element in arr if element != 2]
MartinLwx
  • 1
  • 1
-1

try like this:

arr = [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, "string"]

arr2 = [n for n in arr if n is not 2]

print(arr2)
chacoff
  • 44
  • 3