Mdb
Mdb

Reputation: 13

Count the occurrence of a specific character in all elements of a list of strings

I have a list:

my_list = ['coffee', 'sunshine', 'hiking', 'stocks', 'mountains', 'space', 'Travel']

I would like to count the occurrence of a specific letter across all the elements in that list, let's say the letter 's'.

Can this be achieved without loops?

Upvotes: 0

Views: 166

Answers (2)

Calvin C
Calvin C

Reputation: 1

You can use the map function provided you want the count of the character in each string in the given list.

my_list = ['coffee', 'sunshine', 'hiking', 'stocks', 'mountains', 'space', 'Travel']

count_s = list(map(lambda n: n.count('s'), my_list))
print(count_s)

[0, 2, 0, 2, 1, 1, 0]

Upvotes: 0

Guillaume
Guillaume

Reputation: 2006

Join the words, you then get a string where you can use the count() method to get the number of occurence of a letter.

"".join(my_list).count("a")

Upvotes: 1

Related Questions