title: List Comprehension Method Optimisation
body: <p>I have developed some Python code which revolves around two custom classes - a 'Library' class (Lib) which contains a Python list of several objects based on a 'Cas' class. I've not posted the code for either of these classes here, but all you really need to know to understand my question is that the 'Library' object contains a Python list and the 'Cas' objects contain various attributes, some of which are strings and some are values.</p>
  
  <p>One of the objectives of the code is to manipulate the Python list in the Library class and return a sub-set of the 'Cas' objects based on some user driven criteria. For example, return Cas objects where a particular attribute is equal to a given string or greater than a given value. </p>
  
  <p>For this purpose, I have written the following generic method filterLibrarySingle to allow me to filter the Python list in the library class (self.Lib) based on various methods (filterMethod), attributes (filterField) and values (filterValue). Within the method I'm achieving this using list comprehensions.</p>
  
  <p>On profiling my code, it would appear that this method can be quite a bit of a bottle neck! Does any one have an idea of how I could speed it up?</p>
  
  <pre><code>def filterLibrarySingle(self, filterField, filterMethod, filterValue1, filterValue2=None):
      if filterMethod == 'eq':
          self.Lib = [cas for cas in self.Lib if getattr(cas, filterField) == filterValue1]
  
      elif filterMethod == 'lt':
          self.Lib = [cas for cas in self.Lib if getattr(cas, filterField) &lt; filterValue1]
  
      elif filterMethod == 'gt':
          self.Lib = [cas for cas in self.Lib if getattr(cas, filterField) &gt; filterValue1]
  
      elif filterMethod == 'le':
          self.Lib = [cas for cas in self.Lib if getattr(cas, filterField) &lt;= filterValue1]
  
      elif filterMethod == 'ge':
          self.Lib = [cas for cas in self.Lib if getattr(cas, filterField) &gt;= filterValue1]
  
      elif filterMethod == 'gelt':
          self.Lib = [cas for cas in self.Lib if  getattr(cas, filterField) &gt;= filterValue1 and getattr(cas, filterField) &lt; filterValue2]
  
      elif filterMethod == 'gele':
          self.Lib = [cas for cas in self.Lib if  getattr(cas, filterField) &gt;= filterValue1 and getattr(cas, filterField) &lt;= filterValue2]
  </code></pre>
  
  <p>I've wracked my brains for days on this to try and speed it up but I guess my Python knowledge simply isn't good enough!</p>
  
  <p>I hope someone is able to help improve the performance of this method.</p>
  
  <p>Many thanks</p>
  
  <p>Mark</p>