Skip to content
Advertisement

How to count the number of times a specific character appears in a list?

Okay so here is a list:

sentList = ['I am a dog', 'I am a cat', 'I am a house full of cards']

I want to be able to count the total number of times a user inputted letter appears throughout the entire list.

userLetter = input('Enter a letter: ')

Let’s say the letter is ‘a’

I want the program to go through and count the number of times ‘a’ appears in the list. In this case, the total number of ‘a’ in the list should be 8.

I’ve tried using the count function through a for loop but I keep getting numbers that I don’t know how to explain, and without really knowing how to format the loop, or if I need it at all.

I tried this, but it doesn’t work.

count = sentList.count(userLetter)

Any help would be appreciated, I couldn’t find any documentation for counting all occurrences of a letter in a list.

Advertisement

Answer

Have you tried something like this?

userLetter = input('Enter a letter: ')
sentList = ['I am a dog', 'I am a cat', 'I am a house full of cards']

letterCount = 0
for sentence in sentList:
    letterCount += sentence.count(userLetter)

print("Letter appears {} times".format(letterCount))

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement