Reputation: 11
I am trying to define a function that takes two inputs, a list and an item (could be a string, int, float) and it returns the number of times the item appears in a list. Here's my code:
def count(sequence,item):
for all x in sequence:
if x != item:
while x in sequence:
sequence.remove(x)
return len(sequence)
however, this only deletes the first element not equal to the item in the sequence and deletes it. For example, count([4,8,3],3) returns 2, for it only deletes 4 from the list. I thought the for loop was supposed to take care of that.
Any suggestions?
Upvotes: 1
Views: 299
Reputation: 9394
It is dangerous when you iterate a list and change the length of this list (you use remove())
In your case, When you are iterating the list 'sequence', at first you will get sequence[0] (that is 4). And you remove it. Then, you will get sequence[1]. You suppose sequence[1] is 8. However, because you remove 4 before, now sequence[0] is 8 and sequence[1] is 3. So what you get is not 8 but 3. That is why you can't remove 8 from sequence. You ignore it.
Upvotes: 0
Reputation: 236004
It's as simple as this, using the count
method:
the_list.count(the_item)
From the documentation:
list.count(x)
Return the number of times x appears in the list.
For example:
[1, 2, 3, 1, 4].count(1)
=> 2
And by the way - I don't get it, why are you deleting elements in a function that's supposed to simply count them?
Upvotes: 3