# How to count the "s"?

The below code is returning 2. I think it should be returning 7. Guess it isn’t counting the string `sassafrass` at all?

Code:

``````how_many_s = [{'s': False}, "sassafrass", 18, ["a", "c", "s", "d", "s"]]

for i in how_many_s:
count_s = 0
if hasattr(i, 'count'):
for x in i:
if x == 's':
count_s += 1
print(count_s)
`````````

@petercook0108566555
Happens with me too.
you just need to define count_s variable outside 1st for loop.

``````how_many_s = [{'s': False}, "sassafrass", 18, ["a", "c", "s", "d", "s"]]
count_s = 0
for i in how_many_s:
if hasattr(i, 'count'):
for x in i:
if x == 's':
count_s += 1
print(count_s)
``````
6 Likes

One thinks the idea is to check if the object has the `count` attribute, and if it does, then use it to accumulate the count_s variable.

``````>>> how_many_s = [{'s': False}, "sassafrass", 18, ["a", "c", "s", "d", "s"]]
>>> count_s = 0
>>> for obj in how_many_s:
if hasattr(obj, 'count'):
count_s += obj.count('s')

>>> count_s
7
>>>
``````

Consider,

``````>>> for obj in how_many_s:
print (type(obj)),
if hasattr(obj, 'count'):
count_s += obj.count('s')
print (True)
else:
print (False)

<type 'dict'> False
<type 'str'> True
<type 'int'> False
<type 'list'> True
``````
12 Likes

Thanks. Can you remind my why `count_s = 0` must be outside the For Loop?

That’s like poetry man…

13 Likes

If you put it inside the loop, will it not be reset to zero each time around?

5 Likes

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.

Cause of my English I didnt understand codecademy at all,
but thunks for you guys. I just solved the idea of MTF guru.
So the right answer for me was:

``````how_many_s = [{'s': False}, "sassafrass", 18, ["a", "c", "s", "d", "s"]]
lst =[]
for i in how_many_s:
count_s = 0
if hasattr(i, 'count'):
for x in i:
if x == 's':
count_s += 1
lst.append(count_s)
print(lst)
``````
1 Like

You’re getting 2 because count_s is getting overwritten with each iteration for your first `for` loop. The 2 is the number of ‘s’ in the last iteration (the list). Move the count_s variable above the `for` loop and you should be set.