counters in 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: counter in python

$ python collections_counter_init.py

Counter({'b': 3, 'a': 2, 'c': 1})
Counter({'b': 3, 'a': 2, 'c': 1})
Counter({'b': 3, 'a': 2, 'c': 1})

Example 3: python counter

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

Example 4: python counting dictionary

counts = dict()
for i in items:
  counts[i] = counts.get(i, 0) + 1

Example 5: counter method in python

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

Example 6: counter in python

# import Counter from collections
from collections import Counter
  
# creating a raw data-set using keyword arguments
x = Counter (a = 2, x = 3, b = 3, z = 1, y = 5, c = 0, d = -3)
  
# printing out the elements
for i in x.elements():
    print( "% s : % s" % (i, x[i]), end ="\n")