Python

Python Counter Object

In Python, there are different collection methods available that are used to store the data like list, tuple, etc. But some other methods can track the elements with their frequency value. So, we are going to discuss that collection.

The collections library is an in-built package, so no need to install from the explicit. The collections module has a lot of subclasses, but we are going to discuss the Counter. The counter object returns the value in the dictionary format with the key and value. It is a subclass of the dictionary class.

Creating Python Counter Objects:

Method 1:  Using the list

We can create the object of the counter using the list method. We pass the list as a parameter into the counter function and get back with results in a dictionary format that tells the frequency of each element.

In cell number [4]: We import the collections library, and it is unnecessary to install it explicitly because it is an in-built package.

In cell number [7]: We create a list of alphabet characters and pass them as an argument into that function.

In cell number [8]: We print the count, and we can see that the counter object converts the list into dict with the frequency.

Method 2:  Using a tuple

We can create a counter object by also using a tuple, as shown below in the screenshot.

In cell number [4]: We create a tuple of alphabet characters and pass them as an argument into that function.

In cell number [5]: We print the count_tup, and we can see that the counter object converts the tuple into dict with the frequency.

Method 3:  Creating a Counter object using the string literal

We can also create a counter object using the string literal. We have to pass a string to the counter function, and then the counter object counts each character and displays the result in dict format, as shown below.

In cell number [6]: We pass a string to the counter function and store the result back to a variable name count_str.

In cell number [7]: We print the variable count_str, and the result shows each character in the string with their frequency.

Method 4: Creating a Counter object using the string words list

We can also create a counter object using the list of strings. For that, we have to pass a list of string words to the counter function, and then the counter object counts each word and displays the result in dict format, as shown below.

In cell number [8]: We pass a string list to the counter function and store the result back to a variable name counterWords_list.

In cell number [8]: We print the variable counterWords_list, and the result shows each word in the dict with their frequency.

Method 5: Creating a Counter object using dict

We can also create the counter object using the dict. In dict, it will keep the highest frequency key value in the result as shown below:

In cell number [11]: We pass a dict to the counter function and store the result back to a variable name count_dict.

In cell number [12]: The result shows that the counter chooses the same key value, which has the highest frequency.

Update Counter Object:

The update method helps us to add new elements to an existing counter object. It also allows us to create an empty counter object so that we can use it later.

In cell number [13]: We create an empty counter object with the name counterUpdate. We can use this empty counter object later to either add new elements or update already existing counter object elements.

In cell number [14]: We can see the empty counter.

In cell number [15]: We call the update method using the dot operator and pass a list.

In cell number [16]: We can see the result in dict format with their frequency.

In cell number [17]: We again call the method update to update the existing counter object (counterUpdate).

In cell number [18]: We can see that the frequency of the elements changes because we added new elements to the existing counter.

Accessing count of Elements:

Additionally, we can access the elements of the counter object to know the frequency value. The access elements do not return the exception if that item does not exist in the counter object.

In cell number [19]: We pass a dict into the object.

In cell number [20]: We print our object and see the dict result, decreasing order.

In cell number [21]: We are accessing the count value of the item Dog, which returns a value of 2.

In cell number [22]: We try to access the item [“Rabbit”], but as we know, this item does not exist in the counter, so we get the output 0, not an error.

Updating the count value:

We can also update the count value of the existing element and set the count value of the non-existing element.

In cell number [23]: We pass a dict into the object.

In cell number [24]: We print our object and see the dict result, decreasing order.

In cell number [25]: We are accessing the count value of the item Dog, which returns a value of 2.

In cell number [26]: We set the count value of the “Dog” to 0. So, the value of the count of Dog will become 0. To test that, we print the result in the cell number [27].

In cell number [27]: We can see from the result that the count value of Dog is now 0.

In cell number [29]: We set the new element [“Rabbit”] with the value 1.

In cell number [30]: We print the counter again to check whether the new element “Rabbit” exists or not. As seen, the Rabbit exists in the counter object.

Deleting an Element from the counter

We can also delete an element from the counter object using the del command.

In cell number [31]: We created a dict of a string and passed it to the counter object function.

In cell number [32]: We print our counter object.

In cell number [33]: We use the del keyword to delete an element [“Lion”] from the counter object.

In cell number [34]: We again print our counter object, and the deleted element is confirmed to be removed [“Lion”] inside the string list.

Arithmetic operation on the Counter object:

We can also perform different kinds of arithmetic operations on the counter object. The main operations which we can perform are shown below in the screenshot.

In cell number [35]: We created two objects, counter_1 and counter_2.

In cell number [36]: We apply the addition on two counter objects and print the result. The counter will only show the value that returns positive. That’s why we only got the b value because others have negative values.

In cell number [37]: We apply the subtraction on two counter objects. Like in addition, this also keeps only the positive count value.

In cell number [38]: The intersection we can apply on two counter objects using the single & operator. It returns the minimum value and considers only those elements which are positive. It does not consider even a single negative item like what we have, a= 4 and a = -12, so its minimum value should be 4 but the intersection ignores this because of one negative value.

In cell number [39]: It is opposite to the intersection. It chooses the max value between the two elements, and it also does not ignore the negative value.

The elements ( ) method :

The elements () method works opposite of the counter object. In the counter object, we pass the dict, list, or tuple to count the frequency of the elements and display the result in a dict format. But the elements () convert the dict to list and each element number of times in the list which is equal to their frequency value. It returns the values in an iterator form.

In cell number [40]: We pass a dict object into the counter object function.

In cell number [41]: We call the elements () method using the dot operator and print them. We can see the output saying it is an iterator.

In cell number [42]: We use the list cast function and print all the elements of the dict. In the result, you can see that Cat and Horse are not added because of their values 0 and -1.

Accessing the common elements:

most_common(n):

In cell numbers [44 and 45]: We created a dict object, and passed it to the counter object and printed that object.

In cell number [46]: We call the method most_common() and print. It shows that it is similar to the counter object result because we did not pass any n value so that it shows all elements in a sorted way but decreasing order.

In cell number [47]: We print the most_common with argument value 1, which shows the highest frequency value, Zebra.

In cell number [48]: We print the most_common with argument value 3, which shows the first three elements.

In cell number [49]: The list [: -n: -1] is the standard method to get the least n common elements.

The Subtract () method:

The subtract method is used to subtract the element count value from the counter object.

In cell number [58]: We created a counter object with some string values and printed them in the cell [59].

In cell number [60]: We created another counter object with a single value a.

In cell number [61]: We can see that single dict value of a.

In cell number [62]: We subtract the counter object (a) from the subCounter. After subtracting, we can see that the value printed in the cell [63] now has element ‘a’, which has a count value of 2.

Remove the negative or zero count element

We can also remove the counter object’s negative or zero count elements to having only positive count value elements.

In cell number [68]: We created a counter object with some positive, negative, or zero count value elements.

In cell number [69]: We filter those positive count elements from the counter object. The result shows no negative or zero count elements in the cell [70].

Conclusion:

So we have seen different operations which we can perform on the counter object. We have also discussed methods in creating a counter object. The main ideas which we got from the counter object are below:

  1. The counter object by default prints the elements in decreasing order.
  1. The counter object does not return any error if any item we are trying to access is not in the counter object. It will return the value 0.
  1. The counter object is a subclass of the dict.

Apart from the above main concepts, we learn a lot about the counter object like arithmetic operations, most common elements, updates, etc. We can say that the counter basically keeps track of the elements with their frequency.

The code for this you can download from the link:

https://github.com/shekharpandey89/python-collections-counter

About the author

Shekhar Pandey