Reputation: 187
I am trying to take,as arguments, two values: a list and a target value. It returns the # number of times that the target value appears in the list.
def countTarget(myList, target):
#initialize the counter to zero
counter = 0
for element in myList:
#compare the value in the list to the target value
#if they are the same, increment the counter
if element == target:
counter = counter + 1
return counter
Upvotes: 0
Views: 2132
Reputation: 4550
Use the Counter class. It's a special type of dict that works very well for counting the frequency of a particular value inside a list (as opposed to using a dict yourself) because it will circumvent some nits like running into a KeyError
when trying to count a target that doesn't exist in the list (Counter
on the other hand will just return 0).
from collections import Counter
def countTarget(myList, target):
return Counter(myList)[target]
Alternatively, you can use the bult in count
function for lists, as mentioned in a comment below your question.
def countTarget(myList, target): return myList.count(target)
However, at that point your countTarget
function isn't doing you much good. If you really want to have both objects be parameters, you can also use the count function from a static context...
list.count(myList, target)
But seriously, just use myList.count(target)
. It's probably the most simple and straightforward for your use case (by the looks of it). If you need to count targets multiple times, then consider keeping your own Counter
as mentioned before.
Upvotes: 0
Reputation: 10901
Okay there are going to be better answers, but here's one.
def countTarget(myList, target):
return sum([x == target for x in myList])
Edit
There's a much better alternative in the comments.
myList.count(target)
...
Upvotes: 2