Count


#1

Hi, I'm stuck on the Count exercise: (https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/2/1?curriculum_id=4f89dab3d788890003000096).
I'm not sure where I've gone wrong but the problem seems to arise when the count function is called, in that when I try to call it with both arguments ('sequence' and 'items') inside the function it doesn't work, but when I call the function on 'sequence' with only the argument 'items', it returns the correct answer. Could I please have some advice on how to fix this so that calling the function with both 'sequence' and 'items' as arguments returns the correct answer? Thanks.

def count(sequence, item):
    count = 0
    for i in range(len(sequence)):
        if item == sequence[i]:
            count =+ 1
    return count
    
sequence = [1,1,0,1,1]

print sequence.count(1)
print count(sequence, 1)


#2

Hi, @iharris ,

Check the operator(s) here ...

count =+ 1

How does this affect the value of count? You can temporarily place a print statement within the for loop to find out.


#3

Ah no, what a stupid mistake haha! Fixed it to +=, thanks! :slight_smile:


#4

Hi iharris,
thanks for posting your code. I have been trying in similar way but I did not think about the above syntax. can you please explain what does exactly do and why you have chosen do use it?
Thanks in advance.


#5

Hi :slight_smile:

I used the len function to specify the range in which the loop should iterate through, so that when I use sequence[i], the loop iterates through every index of the list in that range. I hope that helps.


#6

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