One line python code to return all sublists of list containing specific substring in a particluar column
<p>I want to return all the sublists of lists which contains specific substring in a particular column:</p>

<p>For eg:</p>

<pre><code>List=[["2006ab","2005ac"],["2005ab","2004ac"],["2006ab","2005ac"],["2006ab","2003ac"],["2006ab","2005ac"]]
</code></pre>

<p>Search Criteria : Return all sublists which contains substring 2005 at the 2nd index .</p>

<p>Output : </p>

<pre><code>[["2006ab","2005ac"],["2006ab","2005ac"],["2006ab","2005ac"]]
</code></pre>

<p>I tried using : </p>

<pre><code>  matching = [s for s in List if "2005" in s[1]]
</code></pre>

<p>but it returns:</p>

<pre><code>[["2006ab","2005ac"],["2005ab","2004ac"],["2006ab","2005ac"],["2006ab","2005ac"]]
</code></pre>

<p>Your list comprehension approach is good and gives the correct result. Are you sure your code is the same from which you pasted the output because it works for me:</p>

<pre><code>&gt;&gt;&gt; List=[["2006ab","2005ac"],["2005ab","2004ac"],["2006ab","2005ac"],["2006ab","2003ac"],["2006ab","2005ac"]]
&gt;&gt;&gt; [sublist for sublist in List if '2005' in sublist[1]]
[['2006ab', '2005ac'], ['2006ab', '2005ac'], ['2006ab', '2005ac']]
</code></pre>

<p>which is same as what you desire.</p>

<p>If you are looking for an alternative, you may use <code>filter()</code></p>

<pre><code>&gt;&gt;&gt; filter(lambda x: '2005' in x[1], List)
[['2006ab', '2005ac'], ['2006ab', '2005ac'], ['2006ab', '2005ac']]
</code></pre>

python python-2.7 python-3.x filter nested-lists