0

I'm attempting to create a function that finds how many times an item occurs in a function. I have the code below, but it ends up counting all the items in the list(6), not just the one i want( in this case 1). I know i'm not returning anything, the print is mainly for me to see what answer I get.

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

count([1,2,1,2,4,5], 1)
4
  • It should be if item == i. print i also on each iteration. You probably will understand why you should check against i that way. Commented Feb 3, 2016 at 0:30
  • Thanks! Can you tell me why i get 6 when i run as-is? Item in sequence is not found 6 times. Commented Feb 3, 2016 at 0:36
  • Because item is always in sequence. So for every iteration, your code gets into if and increments found. Commented Feb 3, 2016 at 0:37
  • Ok, makes sense. Thanks again! Commented Feb 3, 2016 at 0:39

6 Answers 6

1

try this

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

    count([1,2,1,2,4,5], 1)
Sign up to request clarification or add additional context in comments.

Comments

1

You have to compare element from sequence with item

if i == item:

Comments

1

Do you realize that this method already exists?

return sequence.count(item)

For instance, we get a value of 2 from

my_list = [1,2,1,2,4,5]
print my_list.count(1)

Okay, so you want something harder-headed. :-) How about this?

return len([i for i in sequence if i == item])

1 Comment

This is specifically a method of lists, tuples, and strings, not sequences in general. Good answer though
0

You could use sum and a comprehension

def count(haystack, needle):
    return sum(el==needle for el in haystack)

This will work for any sequence you can iterate over.

>>> s = {"a": None, "b": None, "c": None}
>>> count(s, "a")  # why are you counting a dict? You so crazy....
1

This works because True can be coerced to the integer 1. Summing a sequence of booleans results in the count of Trues in the sequence.

Comments

0

For future reference, python has an awesome Counter class that will do this for you.

from collections import Counter
someList = [1,2,1,2,4,5]
allCounts = Counter(someList) 
print allCounts[1]
print allCounts 

Comments

-2

Python lists support this natively

>>> my_list = [1, 2, 1, 2, 4, 5]
>>> print my_list.count(1)
2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.