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 could replace this with a <code>sum</code> call in which you feed <code>1</code> for every word in <code>wordList</code> that starts with <code>a</code>:</p>

<pre><code>print(sum(1 for w in wordList if w.startswith('a')), 'start with the letter "a"')
</code></pre>

<p>This can be further trimmed down if you use the boolean values returned by <code>startswith</code> instead, since <code>True</code> is treated as <code>1</code> in these contexts the effect is the same:</p>

<pre><code>print(sum(w.startswith('a') for w in a), 'start with the letter "a"')
</code></pre>

<p>With your current approach, you're not summing anything, you're simply printing any word that matches. In addition, you're re-naming <code>a_word</code> from an <code>int</code> to the contents of the list as you iterate through it.</p>

<p>Also, instead of using <code>a_word[0]</code> to check for the first character, you could use <code>startswith(character)</code> which has the same effect and is a bit more readable.</p>

python list python-3.x