counter function python code example

Example 1: counter method in python

from collections import Counter
list1 = ['x','y','z','x','x','x','y','z']
print(Counter(list1))

Example 2: python counter

>>> # Tally occurrences of words in a list
>>> cnt = Counter()
>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
...     cnt[word] += 1
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})

>>> # Find the ten most common words in Hamlet
>>> import re
>>> words = re.findall(r'\w+', open('hamlet.txt').read().lower())
>>> Counter(words).most_common(10)
[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
 ('you', 554),  ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]

Example 3: python counter

>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]

Example 4: counter method in python

from collections import Counter
my_str = "Welcome to Guru99 Tutorials!"
print(Counter(my_str))