Skip to main content

Python Collections Counter Example

Python Counter class is part of Collections module. Counter is used to keep track of elements and their count. The Counter is an unordered collection where elements are stored as dict keys and their count as dict value.

You can store positive, zero or negative integers into the counter. We can also store objects too into the counter. There are number of python counter methods that help to define and manipulate counter.

Python Counter Function

A Counter is a dict subclass for counting hashable objects. There are some important methods available with Counter. We will list down common counter methods python:

  • elements() : This method will return you all the elements with count >0. The Elements with 0 or -1 count will not be returned.
  • most_common(value): This method will return you the most common elements from Counter list.
  • subtract(): This method is used to deduct the elements from another Counter.
  • update(): This method is used to update the elements from another Counter.

How To Create Python Counter Object

You can create python counter and initialize object. We will use collection package and import into the top of the file:

from collections import Counter

How To Define Empty Counter

You can also initialize a empty Counter as shown below:

counter = Counter()
print(counter) # Counter()

Counter with initial values

The Counter supports three forms of initialization. You can initialize counter on a sequence of items, a dictionary containing keys and counts, or using keyword arguments mapping string names to counts.

counter = Counter(x=5, y=6, z=7)
counter = Counter('5', '6', '7')
counter = Counter({'x':4, 'y':6, 'z':7})
print(counter) # Counter({'x': 5, 'y': 6, 'z': 7})

List as argument to Counter

We can also use any Iterable as argument for creating Counter object. We can also use non-numeric data for count values.

color_list = ['Red', 'Green', 'Red', 'Yellow']
counter = Counter(color_list)
print(counter)

Output:

Counter({'Red': 2, 'Green': 1, 'Yellow': 1})

How To Get All Elements of Counter

The elements() method returns the list of elements in the counter. Only elements with positive counts are returned.

counter = Counter({'Red': 2, 'Green': 1, 'Yellow': 1, 'orange': 0})
elements = counter.elements()
print(elements)

Output:

Counter({'Red': 2, 'Green': 1, 'Yellow': 1})

How To Get Count of Element

We can get counter value using existing key. If you are trying to get the count of non-existing key, it will return 0 and not throw KeyError.

counter = Counter({'Red': 2, 'Green': 1, 'Yellow': 1})
cRed = counter['Red']
print(cRed) # 2

Non existing key

print(counter['Orange']) # 0

How To Set Count of Elements

We can also set the count value of existing element in the counter. If the element doesn’t exist, then it gets added to the counter.

counter = Counter({'Red': 2, 'Green': 1, 'Yellow': 1})
counter['Red'] = 4
print(counter['Red']) # 4

How To Set non existing key

counter['Orange'] = 2
print(counter['Orange']) # 2

Delete an element from Counter

We can use del method to delete an element from the counter object.

del counter['Red']
print(counter)

Output:

Counter({'Orange': 2, 'Green': 1, 'Yellow': 1})

Leave a Reply

Your email address will not be published. Required fields are marked *