Python Counter in Collections with Example

Posted in /  

Python Counter in Collections with Example
vinaykhatri

Vinay Khatri
Last updated on November 24, 2024

    Python has a standard library called collections that contains many inbuilt subclasses related to Python containers such as Python list , dict, set, and tuple. Among all the sub-classes available in the collections module, Counter() is the most commonly used. This blog post will explain Python Counter() in collections with examples.

    What is Python Counter() in Collections?

    Python Counter is a sub-class of  the collections module, and it is also referred to as the subclass of dict because it inherits the dict class itself. The Counter() function accepts the Python container object as an argument and returns the count tally of every element in the form of a dictionary. The Counter() module accepts an iterable object like, list, tuple, and string, and returns a dictionary of key:value pairs. Here, keys represent the elements of the iterable object, and values represent their number of occurrences. Note: There is no need for using the Counter() module for iterable objects like sets and dictionaries because sets and dictionaries' keys do not have duplicates.

    Syntax

    from collections import Counter
    Counter(iterable)

    The Counter() module of the collections class accepts an iterable object and returns a counter dictionary object.

    Example

    Let's count the occurrence of every element present in a Python list using the Python Counter() module.

    >>> from collections import Counter
    >>> my_list = [1, 2, 3, 1, 2, 3, "1", "2", "3", "1"]
    >>> count = Counter(my_list)
    >>> count
    Counter({1: 2, 2: 2, 3: 2, '1': 2, '2': 1, '3': 1})

    In the above example, you can see that the Counter() method accepts my_list as an argument and returns a Counter dictionary as the output. The return Counter Dictionary is the pair of Key:Value like a normal Python dictionary. Its keys represent the my_list elements and values represent the number of occurrences of the individual element in my_list .

    Initialize the Counter() Object in Pytho n

    There are four ways to initialize a Counter() object:

    1) Initialize the New Python Empty Counter

    The Python counter object can also be initialized as an empty Counter. To initialize an empty counter object, we just need to specify the Counter() module without any parameters.

    c_obj = Counter()

    Once we have defined an empty counter, we can use the Counter object update() method to count the number of occurrences of every element present in a Python container or iterable.

    c_obj.update(iterable)

    Example

    >>> from collections import Counter
    >>> count = Counter()     #initialize an empty counter 
    >>> fruits = ["apple", "orange","banana","apple", "orange","banana","apple","banana",]
    >>> count.update(fruits)
    >>> print(count)
    Counter({'apple': 3, 'banana': 3, 'orange': 2})

    2) Initialize the Python Counter from an Iterable Object

    For most of the cases, you will be initializing a Counter object from an iterable object. To define a Counter object using an iterable, we pass the iterable as an argument to the Counter() module.

    count = Counter(iterable)

    It is more straightforward than initializing an empty Counter object and then updating it with the update() method. Example

    >>> from collections import Counter
    
    >>> fruits = ["apple", "orange","banana","apple", "orange","banana","apple","banana",]
    >>> count = Counter(fruits)
    
    >>> print(count)
    Counter({'apple': 3, 'banana': 3, 'orange': 2})

    3) Initialize a Counter from Mapping

    When you already know the occurrence of the elements, you can initialize a Counter object as a hashtable object from mapping. For initializing a Counter object from mapping, we pass the dictionary object as an argument to the Counter module. As Python dictionaries are similar to the mapping and hashtable data structures, the Counter module converts the dictionary object to a hashtable object.

    count = Counter(dictionary)

    Example

    >>> from collections import Counter
    
    >>> count = Counter({"apple":3, "banana":3, "orange":2})
    
    >>> print(count)
    Counter({'apple': 3, 'banana': 3, 'orange': 2})

    4) Initialize a Counter Using Keywords Arguments

    We can also initialize the Counter() object using the argument keyword. The initialization of a Counter() object using the keyword argument is similar to initializing it from mapping or dictionary.

    c_obj = Counter(*kwargs)

    Example

    >>> from collections import Counter
    >>> count = Counter(apples=3, bananas=3, oranges=2, grapes=0)
    >>> print(count)
    Counter({'apples': 3, 'bananas': 3, 'oranges': 2, 'grapes':0})

    The Python Counter Module Methods

    The Counter() module itself contains many useful methods such as:

    1. counter_obj.elements()
    2. counter_obj.most_common(element)
    3. counter_obj.substract(c_obj)
    4. counter_obj(update)

    1. Python Counter elements() Method

    The counter elements() method iterates over the counter object dictionary and returns the counter iterable object itertools of all the elements present in the counter dictionary. It iterates over every element the number of times its count and adds them in the iterable object. If the count number of an element is 0, the elements() method ignores it. Syntax

    iterate_obj =counter_obj.elemetns()
    my_elements= list(iterate_obj)  
    

    Example

    >>> from collections import Counter
    
    >>> count = Counter(apples=3, bananas=3, oranges=2, grapes=0)
    
    >>> count
    Counter({'apples': 3, 'bananas': 3, 'oranges': 2, 'grapes': 0})
    
    >>> list(count.elements())
    ['apples', 'apples', 'apples', 'bananas', 'bananas', 'bananas', 'oranges', 'oranges']

    2. Python Counter most_common() Method

    The most_common(n) method returns a list on n tuple pairs (element, count), which has the most number of counts. Syntax

    c_obj.most_common(n)

    Example

    >>> from collections import Counter
    
    >>> count = Counter(apples=3, bananas=3, oranges=2, grapes=0)
    
    >>> count.most_common(2)
    [('apples', 3), ('bananas', 3)]

    3. Python Counter subtract() Method

    The subtract() method of Python Counter in collections subtracts the count number of elements of one Counter object from another counter object. Syntax

    counter1.subtract(counter2)

    Example

    >>> from collections import Counter
    
    >>> shop = Counter(apples=20, bananas=30, oranges=21, grapes=5)
    
    >>> customer = Counter(apples=2, bananas=4, oranges=3)
    
    >>> shop.subtract(customer)
    
    >>> shop
    Counter({'bananas': 26, 'apples': 18, 'oranges': 18, 'grapes': 5})

    4. Python Counter update() Method

    The Python counter update() method can either be used to add a new count element to the Counter object or update the existing count for the existing element. It can either accept an iterable(list, tuple, and string) or a mapping (dictionary) object. Syntax

    count.update(iterable or mapping)

    Example 1

    >>> from collections import Counter
    
    >>> shop = Counter(apples=20, bananas=30, oranges=21, grapes=5)
    
    >>> shop.update(apples=29)   #add 29 more apples to the existing apples
    
    >>> shop
    Counter({'apples': 49, 'bananas': 30, 'oranges': 21, 'grapes': 5})

    Example 2

    >>> from collections import Counter
    
    >>> shop = Counter(apples=20, bananas=30, oranges=21, grapes=5)
    
    >>> shop.update(mangoes=30) #add new element mangoes with count 30
    
    >>> shop
    Counter({'bananas': 30, 'mangoes': 30, 'oranges': 21, 'apples': 20, 'grapes': 5})

    Conclusion

    Python collections is one of the best Python libraries for Python beginners and intermediate developer s . In this Python tutorial, we only discussed one of the subclasses of collections modules here, which is Counter . Nonetheless, there are many other useful sub-classes available in the collections module, such as defaultdict , OrderedDict , deque , and so on. The Python Counter() in the collections module is used to count the number of occurrences of every element present in an iterable object, such as list, tuple, and string. It returns a dictionary type Counter object, where keys represent the elements and values represent their number of occurrences in the iterable object. People are also reading:

    Leave a Comment on this Post

    0 Comments