title: Conditional counting in Python
body: <p>not sure this was asked before, but I couldn't find an obvious answer. I'm trying to count the number of elements in a list that are equal to a certain value. The problem is that these elements are not of a built-in type. So if I have</p>
  
  <pre><code>class A:
      def __init__(self, a, b):
          self.a = a
          self.b = b
  
  stuff = []
  for i in range(1,10):
      stuff.append(A(i/2, i%2))
  </code></pre>
  
  <p>Now I would like a count of the list elements whose field b = 1. I came up with two solutions:</p>
  
  <pre><code>print [e.b for e in stuff].count(1)
  </code></pre>
  
  <p>and</p>
  
  <pre><code>print len([e for e in stuff if e.b == 1])
  </code></pre>
  
  <p>Which is the best method? Is there a better alternative? It seems that the count() method does not accept keys (at least in Python version 2.5.1.</p>
  
  <p>Many thanks!</p>