Fahad Ahammed Fahad Ahammed - 3 months ago 9
Python Question

Python List and remove a variable

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 ?

Answer

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]