Categorize list in Python
<p>What is the best way to categorize a list in python?</p>

<p>for example:</p>

<pre><code>totalist is below

totalist[1] = ['A','B','C','D','E']
totalist[2] = ['A','B','X','Y','Z']
totalist[3] = ['A','F','T','U','V']
totalist[4] = ['A','F','M','N','O']
</code></pre>

<p>Say I want to get the list where the first two items are <code>['A','B']</code>, basically <code>list[1]</code> and <code>list[2]</code>.  Is there an easy way to get these without iterate one item at a time?  Like something like this?</p>

<pre><code>if ['A','B'] in totalist
</code></pre>

<p>I know that doesn't work.</p>

<p>Basically you can't do this in python with a nested list. But if you are looking for an optimized approach here are some ways:</p>

<p>Use a simple list comprehension, by comparing the intended list with only first two items of sub lists:</p>

<pre><code>&gt;&gt;&gt; [sub for sub in totalist if sub[:2] == ['A', 'B']]
[['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'X', 'Y', 'Z']]
</code></pre>

<p>If you want the indices use <code>enumerate</code>:</p>

<pre><code>&gt;&gt;&gt; [ind for ind, sub in enumerate(totalist) if sub[:2] == ['A', 'B']]
[0, 1]
</code></pre>

<p>And here is a approach in Numpy which is pretty much optimized when you are dealing with large data sets:</p>

<pre><code>&gt;&gt;&gt; import numpy as np    
&gt;&gt;&gt; 
&gt;&gt;&gt; totalist = np.array([['A','B','C','D','E'],
...                      ['A','B','X','Y','Z'],
...                      ['A','F','T','U','V'],
...                      ['A','F','M','N','O']])

&gt;&gt;&gt; totalist[(totalist[:,:2]==['A', 'B']).all(axis=1)]
array([['A', 'B', 'C', 'D', 'E'],
       ['A', 'B', 'X', 'Y', 'Z']], 
      dtype='|S1')
</code></pre>

<p>Also as an alternative to list comprehension in python if you don't want to use a loop and you are looking for a functional way, you can use <code>filter</code> function, which is not as optimized as a list comprehension:</p>

<pre><code>&gt;&gt;&gt; list(filter(lambda x: x[:2]==['A', 'B'], totalist))
[['A', 'B', 'C', 'D', 'E'], ['A', 'B', 'X', 'Y', 'Z']]
</code></pre>

python list