15. Count


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:
        times +=1
    return times



Try removing the = from +=1.

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


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):
for i in sequence:
if i == item:
return f


just you should 0 for 1


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;


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.


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.


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


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


Hope this helps :slight_smile:

def count(sequence,item):
    for it in sequence:
        if(item == it):
    return count
print count([1,2,2,1],1)


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


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?



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

If anyone else has a better solution please share.



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