{"id":25900,"date":"2021-12-16T09:20:42","date_gmt":"2021-12-16T03:50:42","guid":{"rendered":"https:\/\/python-programs.com\/?p=25900"},"modified":"2021-12-16T09:20:42","modified_gmt":"2021-12-16T03:50:42","slug":"python-collections-counter-method-with-examples","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-collections-counter-method-with-examples\/","title":{"rendered":"Python collections Counter() Method with Examples"},"content":{"rendered":"

Counter():<\/strong><\/p>\n

The Counter class is a subset of the object data-set offered by Python3’s collections module. The Collections module exposes specialized container datatypes to the user, serving as an alternative to Python’s general-purpose built-ins such as dictionaries, lists, and tuples.<\/p>\n

The counter is a subclass that counts hashable objects. When called, it constructs an iterable hash table implicitly.<\/p>\n

elements() is a function of the Counter class that, when called on a Counter object, returns an itertool of all the known elements in the Counter object.<\/p>\n

Parameters:<\/strong><\/p>\n

 It does not accept any parameters.\r\n\r\n<\/pre>\n

Return type:<\/strong><\/p>\n

 Returns an itertool for every element in the Counter object with a positive count.\r\n\r\n<\/pre>\n

Exceptions and Errors:<\/strong><\/p>\n

Because it returns an itertool rather than a specific data-container, it will output a garbage value when directly printed.\r\n-> If an item's count has already been established in the Counter object, it will ignore items with zero and negative values.<\/pre>\n

Examples:<\/strong><\/p>\n

Example1:<\/strong><\/p>\n

Input:<\/strong><\/p>\n

Given String = \"python-programs\"<\/pre>\n

Output:<\/strong><\/p>\n

p  =  2\r\ny  =  1\r\nt  =  1\r\nh  =  1\r\no  =  2\r\nn  =  1\r\n-  =  1\r\nr  =  2\r\ng  =  1\r\na  =  1\r\nm  =  1\r\ns  =  1<\/pre>\n

Example2:<\/strong><\/p>\n

Input:<\/strong><\/p>\n

Given List=\u00a0[3, 1, 3, 4, 5, 6, 2, 2, 1, 5, 6, 9]<\/pre>\n

Output:<\/strong><\/p>\n

3  =  2\r\n1  =  2\r\n4  =  1\r\n5  =  2\r\n6  =  2\r\n2  =  2\r\n9  =  1<\/pre>\n

Collections Counter() Method with Examples in Python<\/h2>\n