# 15. Count

#1

I can't figure out why the code that I've written doesn't work.

It tells me that "Your function fails on count([4, 'foo', 'foo'],5). It returns 1 when it should return 0."

I tried to see if this was the case so I printed the result of count([4,'foo','foo'],5) and it seems to print 0 as it should.

``````def count(sequence, item):
times = 0
while item in sequence:
sequence.remove(item)
times +=1
return times``````

#2

Hi,

Try removing the = from +=1.

Worked for me though I'm not sure why. Maybe someone else can explain it!

#3

what if you try counting instead of removing items?
just add 1 to the count when your function finds the item in the list

def count(sequence,item):
f=0
for i in sequence:
if i == item:
f+=1
return f

#4

just you should 0 for 1

#5

Hi, I think using for is quite easier. Take a look:

``````def count(sequence, item):
total = 0
for i in sequence:
if i == item:
total += 1
return int(total)``````

Hope it helps;

#6

Yeah, I figured out how to do it this way too. I mostly just wanted to know what the problem with my first method was. Thanks anyway though.

#7

That's really weird. Codecademy says that it's correct when I remove the = but when I actually test it I don't think it gives me the right answers.

#8

def count(sequence, item):
found=0
for i in sequence:
if i == item:
found+=1
return found

#9

Ok i have written this code try it whether it works for you as it worked for me:

def count(sequence, item):
counts = 0
for i in sequence:
if i == item:
counts += 1
return counts

simply taken a count variable initialized to zero and inside a loop checking if i is equal to item .if yes increase count else do nothing. lastly return count

#10

Hope this helps

``````def count(sequence,item):
count=0
for it in sequence:
if(item == it):
count+=1

return count

print count([1,2,2,1],1)``````

#11

change in line 5:
f+=1 to f = f +1 that worked for me:))))

#12

Has anyone try this sequence and item in their code?

print count(11221,1)

In the instruction it said "The item you input may be an integer, string, float, or even another list!"
However, if you try entering the above command in your code you will get an error message. Sequence is an int, hence can't iterate. Anyone find a way around this?

Cheers,

#13

Found a solution, not sure if it is the most efficient but it works.
if type(sequence) == int:
sequence = str(sequence)
else:
sequence = sequence

If anyone else has a better solution please share.

Cheers,

#14

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