Counter

Counter is a container  and it tracks the frequency of values. 

Container is a generic word, which can mean anything that can hold anything. For example, a bucket of water can be considered as container which contains water. Similarly, a list of guests can be considered as another container that holds the list.

The syntax is as follows:

>>>import collections
>>>collections.Counter()

It will be more clear with an example:

In the preceding screenshot, we directly use the Python command line to show the example. Before using Counter, you will need to import the collections module. In the preceding example, we pass on a list of characters to Counter. The Counter processes the list and returns the frequency of each character. Here, frequency means how many times each character occurs within the list. The outcome is in the form of dictionary, where each character of the input list becomes a key and its frequency becomes value for that key. For example, d is the key and 4 is the value which means the character d has appeared four times in the list.

Let's view another example:

We provide sequence of strings directly to the Counter. Here, in this case, even empty spaces are taken into account and their frequency is calculated: 

In this example, we create a list of movies and then pass on the list to the Counter, which returns the frequency of the movies present in the list. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.202.27