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>You imply that you are concerned about performance (cost). If you need to do this, and if you are worried about performance, you need a different data-structure. This will add a little "cost" when you making the lists, but save you time when filtering them. </p>

<p>If the need to filter based on the first two elements is fixed (it doesn't generalise to the first n elements) then I would add the lists, as they are made, to a dict where the key is a tuple of the first two elements, and the item is a list of lists. </p>

<p>then you simply retrieve your list by doing a dict lookup. This is easy to do and will bring potentially large speed ups, at almost no cost in memory and time while making the lists.</p>

python list