Find how many words start with certain letter in a list
<p>I am trying to output the total of how many words start with a letter <code>'a'</code> in a list from a separate text file. I'm looking for an output such as this. </p>

<pre><code>35 words start with a letter 'a'.
</code></pre>

<p>However, i'm outputting all the words that start with an <code>'a'</code> instead of the total with my current code. Should I be using something other than a for loop? </p>

<p>So far, this is what I have attempted:</p>

<pre><code>wordsFile = open("words.txt", 'r')
words = wordsFile.read()
wordsFile.close()
wordList = words.split()

print("Words:",len(wordList)) # prints number of words in the file.

a_words = 0

for a_words in wordList:
    if a_words[0]=='a':
        print(a_words, "start with the letter 'a'.")
</code></pre>

<p>The output I'm getting thus far:</p>

<pre><code>Words: 334
abate start with the letter 'a'.
aberrant start with the letter 'a'.
abeyance start with the letter 'a'.
</code></pre>

<p>and so on.    </p>

<p><code>sum(generator)</code> is a way to go, but for completeness sake, you may want to do it with list comprehension (maybe if it's slightly more readable or you want to do something with words starting with <em>a</em> etc.).</p>

<pre><code>words_starting_with_a = [word for word in word_list if word.startswith('a')]
</code></pre>

<p>After that you may use <code>len</code> built-in to retrieve length of your new list.</p>

<pre><code>print(len(words_starting_with_a), "words start with a letter 'a'")
</code></pre>

python list python-3.x