Python List and remove a variable
<p>I am new to programming. I was trying to understand different data structure in python. In List i was trying:</p>

<pre><code>mylist = [1,2,1,2,1,2,3,4,5,1,2,3]
print mylist
mylist.remove(2)
print mylist
</code></pre>

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

<pre><code>[1, 2, 1, 2, 1, 2, 3, 4, 5, 1, 2, 3]
[1, 1, 2, 1, 2, 3, 4, 5, 1, 2, 3]
</code></pre>

<p>How can i remove all the match ?</p>

<p>Using a list comprehension is probably the most pythonic way of doing this:</p>

<pre><code>mylist = [number for number in mylist if number != 2]
</code></pre>

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

python python-2.7