Indexing an array with a logical array of the same shape in Python
<p>I would like to be able to do:</p>

<pre><code>a = [1,2,3]
a[[True, True, False]]
&gt;&gt; array([1,2])
</code></pre>

<p>I just can't find the simple way how... Thanks!</p>

<p>There's <a href="https://docs.python.org/3.1/library/itertools.html#itertools.compress" rel="nofollow"><code>itertools.compress</code></a>:</p>

<pre><code>&gt;&gt;&gt; from itertools import compress
&gt;&gt;&gt; a = [1,2,3]
&gt;&gt;&gt; mask = [True, True, False]
&gt;&gt;&gt; list(compress(a, mask))
[1, 2]
</code></pre>

<hr>

<p>If you're using <em>numpy</em>, you can slice directly with the mask:</p>

<pre><code>&gt;&gt;&gt; np.array(a)[np.array(mask)]
&gt;&gt;&gt; array([1, 2])
</code></pre>

python