Stergios Katseas
Stergios Katseas

Reputation: 25

Calculating the number of characters inside a list in python

I made a list with some character in it and I looped through it to calculate the number of a specific character and it returns the number of all the characters inside the list and not the one's that I said it to. Take a look at my code and if someone can help I will appreciate it!

This is the code:

array = ['a', 'b', 'c', 'a']
sum_of_as = 0
for i in array:
    if str('a') in array:
        sum_of_as += 1
        
print(f'''The number of a's in this array are {sum_of_as}''')

Upvotes: 1

Views: 1134

Answers (2)

SimonT
SimonT

Reputation: 1019

If you know the list is only ever going to contain single letter strings, as per your example, or if you are searching for a word in a list of words, then you can simply use

list_of_strings = ["a", "b,", "c", "d", "a"]
list_of_strings.count("a")

Be aware though that will not count things such us l = ["ba", "a", "c"] where the response would be 1 as opposed to 2 when searching for a.

The below examples do account for this, so it really does depend on your data and use case.

list_of_strings = ["a", "b,", "c", "d", "ba"]
count = sum(string.count("a") for string in list_of_strings)
print(count)

>>> 2

The above iterates each element of the list and totals up (sums) the amount of times the letter "a" is found, using str.count()

str.count() is a method that returns the number of how many times the string you supply is found in that string you call the method on. This is the equivalent of doing

count = 0
list_of_strings = ["a", "b,", "c", "d", "ba"]
for string in list_of_strings:
    count += string.count("b")
print(count)
name = "david"
print(name.count("d"))

>>> 2

Upvotes: 2

Andrej Kesely
Andrej Kesely

Reputation: 195573

The if str('a') in array evaluates to True in every for-loop iteration, because there is 'a' in the array.

Try to change the code to if i == "a":

array = ["a", "b", "c", "a"]

sum_of_as = 0
for i in array:
    if i == "a":
        sum_of_as += 1

print(sum_of_as)

Prints:

2

OR:

Use list.count:

print(array.count("a"))

Upvotes: 0

Related Questions