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>You are using the <code>a_words</code> as the value of the word in each iteration and missing a counter. If we change the for loop to have <code>words</code> as the value and reserved <code>a_words</code> for the counter, we can increment the counter each time the criteria is passed. You could change <code>a_words</code> to <code>wordCount</code> or something generic to make it more portable and friendly for other letters.</p>

<pre><code>a_words = 0

for words in wordList:
    if words[0]=='a':
        a_words += 1

print(a_words, "start with the letter 'a'.")
</code></pre>

python list python-3.x