Using collection library’s Counter function

Another alternative is using collection library’s Counter function -

>>> from collection import Counter
>>> s = [1,1,1,2,3,3,4,5]
>>> count = Counter(s)
>>> print count
Counter({1: 3, 3: 2, 2: 1, 4: 1, 5: 1})
>>> print count[3]
2

Way ahead of the learning curve here. Gotta object to that post. Moved to General Programming. The learning tracks are rudimentary and deal with fundamentals. Learners are not prepared for heavy hitter techniques or extentions. We don’t want to pressure them, as yet.

1 Like

you can directly use count().

count() is a method of list, tuple and str, but not of set and dict objects. Mind, with sets there can only be one of anything so counting is moot. As we see above, Counter() doesn’t distinguish between keys and values which may skew the results.