Delete similar items that start the same from a list
<p>For example, I have this list:</p>

<pre><code>list = ["192.168.1.1", "0.1.2.3", "0.2.3.4", "192.168.1.2", "0.3.4.5", "192.168.1.3"]
</code></pre>

<p>How can I remove with a command all the items that start with <code>"0."</code>?</p>

<p>You can filter the desired items in a list using a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a> using <a href="https://docs.python.org/2/library/stdtypes.html#str.startswith" rel="nofollow"><code>str.startswith()</code></a> to check if a string starts with "0.":</p>

<pre><code>&gt;&gt;&gt; l = ['192.168.1.1', '0.1.2.3', '1.2.3.4', '192.168.1.2', '0.3.4.5', '192.168.1.3']
&gt;&gt;&gt; [item for item in l if not item.startswith('0.')]
['192.168.1.1', '1.2.3.4', '192.168.1.2', '192.168.1.3']
</code></pre>

<p>Note that <code>list</code> is not a good variable name - it <em><a href="https://en.wikipedia.org/wiki/Variable_shadowing" rel="nofollow">shadows</a> the built-in <code>list</code></em>.</p>

<hr>

<p>You can also approach the problem with <a href="https://docs.python.org/3/library/functions.html#filter" rel="nofollow"><code>filter()</code></a> and a filtering function:</p>

<pre><code>&gt;&gt;&gt; list(filter(lambda x: not x.startswith("0."), l))
['192.168.1.1', '1.2.3.4', '192.168.1.2', '192.168.1.3']
</code></pre>

<p>Note that in Python 3.x, unlike Python 2.x, <code>filter()</code> returns an <em>iterator</em>, hence, calling <code>list()</code> to demonstrate the result.</p>

<hr>

<p>And, a "just for fun" option and to demonstrate how can you overcomplicate the problem with different functional programming-style tools:</p>

<pre><code>&gt;&gt;&gt; from operator import methodcaller
&gt;&gt;&gt; from itertools import filterfalse
&gt;&gt;&gt;
&gt;&gt;&gt; list(filterfalse(methodcaller('startswith', "0."), l))
['192.168.1.1', '1.2.3.4', '192.168.1.2', '192.168.1.3']
</code></pre>

<p><a href="https://docs.python.org/3/library/itertools.html#itertools.filterfalse" rel="nofollow"><code>itertools.filterfalse()</code></a> and <a href="https://docs.python.org/3/library/operator.html#operator.methodcaller" rel="nofollow"><code>operator.methodcaller()</code></a> were used.</p>

python list python-3.x