title: Python: Elegant and efficient ways to mask a list
body: <p><strong>Example:</strong>  </p>
  
  <pre><code>from __future__ import division
  import numpy as np
  
  n = 8
  """masking lists"""
  lst = range(n)
  print lst
  
  # the mask (filter)
  msk = [(el&gt;3) and (el&lt;=6) for el in lst]
  print msk
  
  # use of the mask
  print [lst[i] for i in xrange(len(lst)) if msk[i]]
  
  """masking arrays"""
  ary = np.arange(n)
  print ary
  
  # the mask (filter)
  msk = (ary&gt;3)&amp;(ary&lt;=6)
  print msk
  
  # use of the mask
  print ary[msk]                          # very elegant  
  </code></pre>
  
  <p>and the results are:  </p>
  
  <pre><code>&gt;&gt;&gt; 
  [0, 1, 2, 3, 4, 5, 6, 7]
  [False, False, False, False, True, True, True, False]
  [4, 5, 6]
  [0 1 2 3 4 5 6 7]
  [False False False False  True  True  True False]
  [4 5 6]
  </code></pre>
  
  <p>As you see the operation of masking on array is more elegant compared to list. If you try to use the array masking scheme on list you'll get an error:  </p>
  
  <pre><code>&gt;&gt;&gt; lst[msk]
  Traceback (most recent call last):
    File "&lt;interactive input&gt;", line 1, in &lt;module&gt;
  TypeError: only integer arrays with one element can be converted to an index
  </code></pre>
  
  <p>The question is to find an elegant masking for <code>list</code>s.</p>
  
  <p><strong>Updates:</strong><br>
  The answer by <code>jamylak</code> was accepted for introducing <code>compress</code> however the points mentioned by <code>Joel Cornett</code> made the solution complete to a desired form of my interest.</p>
  
  <pre><code>&gt;&gt;&gt; mlist = MaskableList
  &gt;&gt;&gt; mlist(lst)[msk]
  &gt;&gt;&gt; [4, 5, 6]
  </code></pre>