{"id":1585,"date":"2019-12-27T13:16:30","date_gmt":"2019-12-27T13:16:30","guid":{"rendered":"https:\/\/www.askpython.com\/?p=1585"},"modified":"2022-08-06T13:17:15","modified_gmt":"2022-08-06T13:17:15","slug":"counter-in-python","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/counter-in-python","title":{"rendered":"Counter in Python"},"content":{"rendered":"\n<p>A Counter is a subclass of <code>dict<\/code> and is part of the <strong>Collections<\/strong> module. It is used for counting hashable objects.<\/p>\n\n\n\n<p>It is an unordered collection where the elements are stored as Dictionary Keys and their counts are the values.<\/p>\n\n\n\n<p>Counter Object format: <code>{element1: count1, element2: count2}<\/code><\/p>\n\n\n\n<p>Elements are counted from an\u00a0<em>iterable<\/em>\u00a0or initialized from another mapping\u00a0(or counter)<\/p>\n\n\n\n<p>Initialization of the <code>Counter<\/code> object is done using the <code>Counter()<\/code> call.<\/p>\n\n\n\n<p>We can also pass an iterable into the call and get the corresponding mapped object.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&gt;&gt;&gt; from collections import Counter\n&gt;&gt;&gt; # Empty Counter object\n&gt;&gt;&gt; c = Counter()\n&gt;&gt;&gt; c\nCounter()\n\n&gt;&gt;&gt; # Tuple of values\n&gt;&gt;&gt; d = Counter(a=1, b=2, c=1)\n&gt;&gt;&gt; d\nCounter({&#039;b&#039;: 2, &#039;a&#039;: 1, &#039;c&#039;: 1})\n\n&gt;&gt;&gt; # Pass a list, which is an iterable\n&gt;&gt;&gt; e = Counter(&#x5B;&#039;a&#039;, &#039;b&#039;, &#039;a&#039;, &#039;c&#039;])\n&gt;&gt;&gt; e\nCounter({&#039;a&#039;: 2, &#039;b&#039;: 1, &#039;c&#039;: 1})\n\n&gt;&gt;&gt; # Pass a string, also an iterable\n&gt;&gt;&gt; f = Counter(&#039;red-dish&#039;)\n&gt;&gt;&gt; f\nCounter({&#039;d&#039;: 2, &#039;r&#039;: 1, &#039;e&#039;: 1, &#039;-&#039;: 1, &#039;i&#039;: 1, &#039;s&#039;: 1, &#039;h&#039;: 1})\n\n&gt;&gt;&gt; # Pass a Dictionary\n&gt;&gt;&gt; g = Counter({&#039;a&#039;: 10, &#039;b&#039;: 11})\n&gt;&gt;&gt; g\nCounter({&#039;b&#039;: 11, &#039;a&#039;: 10})\n<\/pre><\/div>\n\n\n<p>Note that when the Counter object is displayed, the key-value pairs are displayed on the order of descending counts.<\/p>\n\n\n\n<p>Counter objects have a dictionary interface except that they return a zero count for missing items instead of raising a <code><a href=\"https:\/\/docs.python.org\/2\/library\/exceptions.html#exceptions.KeyError\" target=\"_blank\" rel=\"noopener\">KeyError<\/a><\/code>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Counter Methods<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">1. Get the count of individual elements<\/h3>\n\n\n\n<p>Individual element counts are accessed in the same way as that of a Dictionary, meaning that <code>counter_object[key]<\/code> gives the count of <code>key<\/code>.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&gt;&gt;&gt; c = Counter(a=1, b=2, c=1)\n&gt;&gt;&gt; c\nCounter({&#039;b&#039;: 2, &#039;a&#039;: 1, &#039;c&#039;: 1})\n&gt;&gt;&gt; c&#x5B;&#039;b&#039;]\n2\n&gt;&gt;&gt; c&#x5B;&#039;d&#039;] # Does not give KeyError, unlike a Dictionary\n0\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">2. Set the count of elements<\/h3>\n\n\n\n<p>To set the count of an element, use <code>counter_object[key] = value<\/code>. If <code>key<\/code> does not exist, it gets added to the Counter Dictionary, along with the new count.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&gt;&gt;&gt; c = Counter(a=1, b=2, c=1)\n&gt;&gt;&gt; c\nCounter({&#039;b&#039;: 2, &#039;a&#039;: 1, &#039;c&#039;: 1})\n&gt;&gt;&gt; c&#x5B;&#039;d&#039;] = 4\n&gt;&gt;&gt; c\nCounter({&#039;d&#039;: 4, &#039;b&#039;: 2, &#039;a&#039;: 1, &#039;c&#039;: 1})\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">3. Remove elements from the Counter<\/h3>\n\n\n\n<p>To remove a key from the Counter object, use <code>del counter_object[key]<\/code>.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&gt;&gt;&gt; del c&#x5B;&#039;d&#039;]\n&gt;&gt;&gt; c\nCounter({&#039;b&#039;: 2, &#039;a&#039;: 1, &#039;c&#039;: 1})\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">4. elements()<\/h3>\n\n\n\n<p>This method returns an iterator over the elements, values of which are repeated as many times as their counts. This method ignores <em>all<\/em> elements that have their counts less than one.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&gt;&gt;&gt; c\nCounter({&#039;b&#039;: 2, &#039;a&#039;: 1, &#039;c&#039;: 1})\n&gt;&gt;&gt; c&#x5B;&#039;d&#039;] = -1\n&gt;&gt;&gt; c\n&gt;&gt;&gt; c.elements()\n&lt;itertools.chain object at 0x102e2a208&gt;\n&gt;&gt;&gt; type(c.elements())\n&lt;class &#039;itertools.chain&#039;&gt;\n&gt;&gt;&gt; for i in c.elements():\n...     print(i)\n...\na\nb\nb\nc\n&gt;&gt;&gt; list(c.elements())\n&#x5B;&#039;a&#039;, &#039;b&#039;, &#039;b&#039;, &#039;c&#039;]\n\n&gt;&gt;&gt; c&#x5B;&#039;d&#039;] = -1\n&gt;&gt;&gt; c\nCounter({&#039;b&#039;: 2, &#039;a&#039;: 1, &#039;c&#039;: 1, &#039;d&#039;: -1})\n&gt;&gt;&gt; # Ignores d since count&#x5B;d] &lt; 1\n&gt;&gt;&gt; list(c.elements())\n&#x5B;&#039;a&#039;, &#039;b&#039;, &#039;b&#039;, &#039;c&#039;]\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">5. most_common(n)<\/h3>\n\n\n\n<p>This returns a list of the <em>n<\/em> most common elements and their counts from the most common to the least. If <em>n<\/em> is omitted or <code>None<\/code>, <code><em>most_common()<\/em><\/code> returns <em>all<\/em> elements in the counter. Elements with equal counts are ordered arbitrarily.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&gt;&gt;&gt; c\nCounter({&#039;b&#039;: 2, &#039;a&#039;: 1, &#039;c&#039;: 1, &#039;d&#039;: -1})\n&gt;&gt;&gt; c.most_common()\n&#x5B;(&#039;b&#039;, 2), (&#039;a&#039;, 1), (&#039;c&#039;, 1), (&#039;d&#039;, -1)]\n&gt;&gt;&gt; c.most_common(2)\n&#x5B;(&#039;b&#039;, 2), (&#039;a&#039;, 1)]\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">6. subtract(iterable\/mapping)<\/h3>\n\n\n\n<p>This returns a mapping\/iterable after subtracting the contents of the two iterables\/mappings. Elements are not replaced, and only their counts are subtracted.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&gt;&gt;&gt; a = Counter(&#039;redblue&#039;)\n&gt;&gt;&gt; a\nCounter({&#039;e&#039;: 2, &#039;r&#039;: 1, &#039;d&#039;: 1, &#039;b&#039;: 1, &#039;l&#039;: 1, &#039;u&#039;: 1})\n&gt;&gt;&gt; b = Counter(&#039;blueorange&#039;)\n&gt;&gt;&gt; b\nCounter({&#039;e&#039;: 2, &#039;b&#039;: 1, &#039;l&#039;: 1, &#039;u&#039;: 1, &#039;o&#039;: 1, &#039;r&#039;: 1, &#039;a&#039;: 1, &#039;n&#039;: 1, &#039;g&#039;: 1})\n\n&gt;&gt;&gt; # Subtracts b from a and updates a accordingly\n&gt;&gt;&gt; a.subtract(b)\n&gt;&gt;&gt; a\nCounter({&#039;d&#039;: 1, &#039;r&#039;: 0, &#039;e&#039;: 0, &#039;b&#039;: 0, &#039;l&#039;: 0, &#039;u&#039;: 0, &#039;o&#039;: -1, &#039;a&#039;: -1, &#039;n&#039;: -1, &#039;g&#039;: -1})\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">7. update(iterable\/mapping)<\/h3>\n\n\n\n<p>This is similar to <code>subtract()<\/code>, but only adds counts instead of subtracting them.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&gt;&gt;&gt; a = Counter(&#039;12321&#039;)\n&gt;&gt;&gt; b = Counter(&#039;23432&#039;)\n&gt;&gt;&gt; a\nCounter({&#039;1&#039;: 2, &#039;2&#039;: 2, &#039;3&#039;: 1})\n&gt;&gt;&gt; b\nCounter({&#039;2&#039;: 2, &#039;3&#039;: 2, &#039;4&#039;: 1})\n\n&gt;&gt;&gt; # Add counts into a\n&gt;&gt;&gt; a.update(b)\n&gt;&gt;&gt; a\nCounter({&#039;2&#039;: 4, &#039;3&#039;: 3, &#039;1&#039;: 2, &#039;4&#039;: 1})\n<\/pre><\/div>\n\n\n<h2 class=\"wp-block-heading\">Other Counter() methods<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li><code><strong><em>counter.clear()<\/em><\/strong><\/code> is used to reset the counts of all elements in the Counter<\/li><li><code><strong><em>counter.values()<\/em><\/strong><\/code> returns a <em>dict-values<\/em> object, used for other methods such as <code>sum()<\/code> to get the total count of all elements.<\/li><li><code><strong><em>list(counter)<\/em><\/strong><\/code> is used to list all unique elements<\/li><li><code><strong><em>set(counter)<\/em><\/strong><\/code> converts the counter into a Set<\/li><li><code><strong><em>counter.items()<\/em><\/strong><\/code> returns a list of <code>(key, value)<\/code> pairs in the Counter.<\/li><li><code><strong><em>counter += Counter()<\/em><\/strong><\/code> removes all elements with zero or negative counts<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Arithmetic Operations on Counters<\/h2>\n\n\n\n<p>We can use basic arithmetic operations on Counters, like addition, subtraction, union, and intersection.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n&gt;&gt;&gt; c = Counter(a=3, b=1)\n&gt;&gt;&gt; d = Counter(a=1, b=2)\n&gt;&gt;&gt; c + d\nCounter({&#039;a&#039;: 4, &#039;b&#039;: 3})\n\n&gt;&gt;&gt; # Subtract c, d while keeping only positive counts\n&gt;&gt;&gt; c - d\nCounter({&#039;a&#039;: 2})\n\n&gt;&gt;&gt; # Intersection of c, d (Min(c, d))\n&gt;&gt;&gt; c &amp; d\nCounter({&#039;a&#039;: 1, &#039;b&#039;: 1})\n\n&gt;&gt;&gt; # Union of c, d (Max (c, d))\n&gt;&gt;&gt; c | d\nCounter({&#039;a&#039;: 3, &#039;b&#039;: 2})\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>We learned about the Counter class, which gives us objects having a mapping to each element to its count. We also learned about some of the methods that collections.Counter provides us with, for manipulating the Counter objects.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">References<\/h2>\n\n\n\n<p>Python Collections Documentation: <a href=\"https:\/\/docs.python.org\/2\/library\/collections.html\" target=\"_blank\" rel=\"noopener\">https:\/\/docs.python.org\/2\/library\/collections.html<\/a><\/p>\n\n\n\n<p>JournalDev Article on Python&#8217;s Counter: https:\/\/www.journaldev.com\/20806\/python-counter-python-collections-counter<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n","protected":false},"excerpt":{"rendered":"<p>A Counter is a subclass of dict and is part of the Collections module. It is used for counting hashable objects. It is an unordered collection where the elements are stored as Dictionary Keys and their counts are the values. Counter Object format: {element1: count1, element2: count2} Elements are counted from an\u00a0iterable\u00a0or initialized from another [&hellip;]<\/p>\n","protected":false},"author":7,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-1585","post","type-post","status-publish","format-standard","hentry","category-python"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/1585","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=1585"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/1585\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=1585"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=1585"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=1585"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}