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>You can use 
<a href="https://docs.python.org/2/library/functions.html#filter" rel="nofollow">filter</a></p>

<pre><code>&gt;&gt;&gt; mylist = [1,2,1,2,1,2,3,4,5,1,2,3]
&gt;&gt;&gt; filter(lambda x:x!=2, mylist)
[1, 1, 1, 3, 4, 5, 1, 3]
</code></pre>

<p>Or simple list comprehension.</p>

<pre><code>my_list = [i for i in my_list if i!=2]
</code></pre>

<p>You can even use <code>remove()</code> to get the correct result by doing this:</p>

<pre><code>&gt;&gt;&gt; while True:
...     try:
...         mylist.remove(2)
...     except:
...         break
... 
&gt;&gt;&gt; mylist
[1, 1, 1, 3, 4, 5, 1, 3]
</code></pre>

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

python python-2.7