'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.



Solution 1:[1]

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))

Solution 2:[2]

Use the sum() builtin to add up the counts for each string in the list:

total = sum(s.count(userLetter) for s in sentList)

Solution 3:[3]

Merge all the strings into a single string and then use the count function.

count = ''.join(sentList).count(userLetter)

Solution 4:[4]

Your approach is halfway correct. The problem is that you need to go through the list.

word_count=0
for l in sentList:
     word_count+= l.count(userLetter)

Solution 5:[5]

word_list = ["aardvark", "baboon", "camel"] import random chosen_word = random.choice(word_list) guess = input("Guess a letter: ").lower()

for letter in chosen_word: if letter == guess: print("Right") else: print("Wrong")

Solution 6:[6]

example program to check if entered letter is present in random choice of word

word_list = ["aardvark", "baboon", "camel"]

import random

chosen_word = random.choice(word_list)

guess = input("Guess a letter: ").lower()

for letter in chosen_word:

    if letter == guess:

        print("Right")
    else:

        print("Wrong")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joe Davy
Solution 2 aghast
Solution 3
Solution 4 Kaushik NP
Solution 5 Nadia Sharief
Solution 6 PM 77-1