"pythonic" way to fill bag of words
<p>I've got a list of words, about 273000 of them in the list <code>Word_array</code>
There are about 17000 unique words, and they're stored in <code>Word_arrayU</code></p>

<p>I want a count for each one</p>

<pre><code>#make bag of worsds   
Word_arrayU = np.unique(Word_array)
wordBag = [['0','0'] for _ in range(len(Word_array))] #prealocate necessary space
i=0
while i&lt; len(Word_arrayU): #for each unique word
    wordBag[i][0] = Word_arrayU[i]
    #I think this is the part that takes a long time.  summing up a list comprehension with a conditional.  Just seems sloppy
    wordBag[i][1]=sum([1 if x == Word_arrayU[i] else 0 for x in Word_array])
    i=i+1
</code></pre>

<p>summing up a list comprehension with a conditional.  Just seems sloppy; is there a better way to do it?</p>

<p>Building on the suggestion from @jonrsharpe...</p>

<pre><code>from collections import Counter

words = Counter()

words['foo'] += 1
words['foo'] += 1
words['bar'] += 1
</code></pre>

<p>Output</p>

<pre><code>Counter({'bar': 1, 'foo': 2})
</code></pre>

<p>It's really convenient because you don't have to initialize words.</p>

<p>You can also initialize directly from a list of words:</p>

<pre><code>Counter(['foo', 'foo', 'bar'])
</code></pre>

<p>Output</p>

<pre><code>Counter({'bar': 1, 'foo': 2})
</code></pre>

python string counter