"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>In python 3 there is a built-in list.count function. For example:</p>

<pre><code>&gt;&gt;&gt; h = ["a", "b", "a", "a", "c"]
&gt;&gt;&gt; h.count("a")
3
&gt;&gt;&gt; 
</code></pre>

<p>So, you could make it more efficient by doing something like:</p>

<pre><code>Word_arrayU = np.unique(Word_array)
wordBag = []
for uniqueWord in Word_arrayU:
    wordBag.append([uniqueWord, Word_array.count(uniqueWord)])
</code></pre>

python string counter