0
a = [1, 2, 2]
value = 2 
for i in a:
 if i == value:
    a.remove(i)

I want to delete 2 same elements in a list. But the result tells me I just delete one of them. when I debug it, I find it only cycle 2 times, not 3 as I wish.

Field
  • 3
  • 2

2 Answers2

0

Here you don't have to use a comparison to remove a certain value from list

Here is a little modification to your code:

a = [1, 2, 2]
value = 2

try:
    for i in a: a.remove (value)
except ValueError: pass

print (a)

Whenever the remove () function couldn't find the value you are looking for, it will raise a value error: ValueError: list.remove(x): x not in list. To eliminate this, surround it with a try except. That'll do the trick.

However there are more easier methods to use remove () function. For an example you could use while loop.

Look at this code:

a = [1, 2, 2]
value = 2

while value in a:
    a.remove (value)

print (a)

Its far more easier.

ahrooran
  • 931
  • 1
  • 10
  • 25
  • Thanks a lot. By the way, I don't know why the code I wrote above by for-loop cannot work – Field Dec 14 '18 at 09:52
0

You can use a simple list comprehension for a 1-line solution:

In [2764]: a = [1, 2, 2]
In [2755]: value = 2

In [2768]: a = [i for i in a if i != value]

In [2769]: a
Out[2769]: [1]

You can write the above as :

ans = []
for i in a:
    if i <> value:
    ans.append(i)

OR, you can also use filter to remove all occurrences:

Python-2

In [2778]: filter(lambda x: x!= value, a)
Out[2778]: [1]

Python-3

In [5]: list(filter(lambda x: x!= value, a))
Out[5]: [1]
Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
  • The `list comprehension` method I wrote is basically a `for loop` only. Check my answer. I wrote the `for` equivalent of `list comprehension`. That is how you should write your for loop. – Mayank Porwal Dec 14 '18 at 10:00
  • ok, maybe I should learn about this way – Field Dec 14 '18 at 10:03