Comparing two list and getting a new list in python
<p>I have a list - a and a list of columns - b.</p>

<pre><code>a = [2, 4, 1, 1, 6, 1, 1, 3, 5, 1]
b = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
</code></pre>

<p>I want to take the columns from list "b" which when compared with list "a" have the value 1.</p>

<p>I want the output to be:</p>

<pre><code>c = ["C", "D", "F", "G", "J"]
</code></pre>

<p>How can I do it?</p>

<p>Done in many ways:</p>

<p><strong>List Comprehension</strong></p>

<pre><code>a = [2, 4, 1, 1, 6, 1, 1, 3, 5, 1]
b = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
print [b[index] for index, item in enumerate(a) if item == 1]
</code></pre>

<p><strong>Filter with Lambda</strong></p>

<pre><code>a = [2, 4, 1, 1, 6, 1, 1, 3, 5, 1]
b = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
print filter(lambda index, item: len(a) &gt; index and a[index]==1, enumerate(b))
</code></pre>

<p>Note that the list comprehension will be faster because it goes only up to the length of a rather than the list b, in case b is bigger.</p>

python list