0

I am new to programming. I was trying to understand different data structure in python. In List i was trying:

mylist = [1,2,1,2,1,2,3,4,5,1,2,3]
print mylist
mylist.remove(2)
print mylist

It is supposed to remove 2 from the list. It does but the first one only. The output is like:

[1, 2, 1, 2, 1, 2, 3, 4, 5, 1, 2, 3]
[1, 1, 2, 1, 2, 3, 4, 5, 1, 2, 3]

How can i remove all the match ?

Fahad Ahammed
  • 371
  • 1
  • 11
  • 23
  • Thanks everyone. List Comprehension seems the right one for me. But i am confused which one i should select as answer. Thanks guys for answer. – Fahad Ahammed Aug 27 '16 at 11:02
  • Possible duplicate of [Remove all occurrences of a value from a Python list](http://stackoverflow.com/questions/1157106/remove-all-occurrences-of-a-value-from-a-python-list) – Julien Aug 27 '16 at 11:19
  • But it is almost much more clearer question and answer. – Fahad Ahammed Aug 27 '16 at 12:08

6 Answers6

4

You can use filter

>>> mylist = [1,2,1,2,1,2,3,4,5,1,2,3]
>>> filter(lambda x:x!=2, mylist)
[1, 1, 1, 3, 4, 5, 1, 3]

Or simple list comprehension.

my_list = [i for i in my_list if i!=2]

You can even use remove() to get the correct result by doing this:

>>> while True:
...     try:
...         mylist.remove(2)
...     except:
...         break
... 
>>> mylist
[1, 1, 1, 3, 4, 5, 1, 3]

But, this is ugly, and often causes unexpected behavior. You should never modify a list while iterating.

Ahsanul Haque
  • 10,676
  • 4
  • 41
  • 57
1
mylist = [x for x in mylist if x != 2]

This is simpler than a filter.

Rory Daulton
  • 21,934
  • 6
  • 42
  • 50
1

Using a list comprehension is probably the most pythonic way of doing this:

mylist = [number for number in mylist if number != 2]

This is because list.remove(x) only removes the first occurrence of x in the list. The above solution will create a new list based on mylist that will contain all elements of mylist if they are unequal to 2.

Dartmouth
  • 1,069
  • 2
  • 15
  • 22
1

According to docs, this behavior is expected:

list.remove(x)

Remove the first item from the list whose value is x. It is an error if there is no such item.

To remove all occurences of value from list you may use list comprehension:

seq = [1,2,1,2,1,2,3,4,5,1,2,3]
seq = [value for value in seq in value != 2]
Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93
1

From python help:

help(list.remove)

you can get this explanation:

L.remove(value) -- remove first occurrence of value. Raises ValueError if the value is not present.

You can achieve it by using list comprehension:

mylist = [x for x in mylist if x != 2]

It just create a new list according to your conditions.

turkus
  • 4,637
  • 2
  • 24
  • 28
0

another way(if you wont create new list):

while 2 in mylist:
    mylist.remove(2)
Alireza Afzal Aghaei
  • 1,184
  • 10
  • 27