Python Counter - Python Collections Counter | DigitalOcean (2024)

Python Counter class is part of Collections module. Counter is a subclass of Dictionary and used to keep track of elements and their count.

Python Counter

Counter is an unordered collection where elements are stored as Dict keys and their count as dict value. Counter elements count can be positive, zero or negative integers. However there is no restriction on it’s keys and values. Although values are intended to be numbers but we can store other objects too.

Creating Python Counter Object

We can create an empty Counter or start with some initial values too.

from collections import Counter# empty Countercounter = Counter()print(counter) # Counter()# Counter with initial valuescounter = Counter(['a', 'a', 'b'])print(counter) # Counter({'a': 2, 'b': 1})counter = Counter(a=2, b=3, c=1)print(counter) # Counter({'b': 3, 'a': 2, 'c': 1})

We can also use any Iterable as argument for creating Counter object. So string literal and List can be used too for creating Counter object.

# Iterable as argument for Countercounter = Counter('abc')print(counter) # Counter({'a': 1, 'b': 1, 'c': 1})# List as argument to Counterwords_list = ['Cat', 'Dog', 'Horse', 'Dog']counter = Counter(words_list)print(counter) # Counter({'Dog': 2, 'Cat': 1, 'Horse': 1})# Dictionary as argument to Counterword_count_dict = {'Dog': 2, 'Cat': 1, 'Horse': 1}counter = Counter(word_count_dict)print(counter) # Counter({'Dog': 2, 'Cat': 1, 'Horse': 1})

As I mentioned above, we can use non-numeric data for count values too, but that will defect the purpose of Counter class.

# Counter works with non-numbers toospecial_counter = Counter(name='Pankaj', age=20)print(special_counter) # Counter({'name': 'Pankaj', 'age': 20})

Python Counter Methods

Let’s look into Counter class methods and some other operations we can perform on it.

Getting Count of Elements

# getting countcounter = Counter({'Dog': 2, 'Cat': 1, 'Horse': 1})countDog = counter['Dog']print(countDog) # 2

If we try to get the count of non-existing key, it will return 0 and not throw KeyError.

# getting count for non existing key, don't cause KeyErrorprint(counter['Unicorn']) # 0

Setting Count of Elements

We can also set the count of existing element in the counter. If the element doesn’t exist, then it gets added to the counter.

counter = Counter({'Dog': 2, 'Cat': 1, 'Horse': 1})# setting countcounter['Horse'] = 0print(counter) # Counter({'Dog': 2, 'Cat': 1, 'Horse': 0})# setting count for non-existing key, adds to Countercounter['Unicorn'] = 1print(counter) # Counter({'Dog': 2, 'Cat': 1, 'Unicorn': 1, 'Horse': 0})

Deleting an element from Counter

We can use del to delete an element from the counter object.

# Delete element from Counterdel counter['Unicorn']print(counter) # Counter({'Dog': 2, 'Cat': 1, 'Horse': 0})

elements()

This method returns the list of elements in the counter. Only elements with positive counts are returned.

counter = Counter({'Dog': 2, 'Cat': -1, 'Horse': 0})# elements()elements = counter.elements() # doesn't return elements with count 0 or lessfor value in elements: print(value)

Above code will print “Dog” two times because it’s count is 2. Other elements will be ignored because they don’t have positive count. Counter is an unordered collection, so elements are returned in no particular order.

most_common(n)

This method returns the most common elements from the counter. If we don’t provide value of ‘n’ then sorted dictionary is returned from most common the least common elements. We can use slicing to get the least common elements on this sorted dictionary.

counter = Counter({'Dog': 2, 'Cat': -1, 'Horse': 0})# most_common()most_common_element = counter.most_common(1)print(most_common_element) # [('Dog', 2)]least_common_element = counter.most_common()[:-2:-1]print(least_common_element) # [('Cat', -1)]

subtract() and update()

Counter subtract() method is used to subtract element counts from another counter. update() method is used to add counts from another counter.

counter = Counter('ababab')print(counter) # Counter({'a': 3, 'b': 3})c = Counter('abc')print(c) # Counter({'a': 1, 'b': 1, 'c': 1})# subtractcounter.subtract(c)print(counter) # Counter({'a': 2, 'b': 2, 'c': -1})# updatecounter.update(c)print(counter) # Counter({'a': 3, 'b': 3, 'c': 0})

Python Counter Arithmetic Operations

We can perform some arithmetic operations on Counters too, just like numbers. However only elements with positive count are returned with these operations.

# arithmetic operationsc1 = Counter(a=2, b=0, c=-1)c2 = Counter(a=1, b=-1, c=2)c = c1 + c2 # return items having +ve count onlyprint(c) # Counter({'a': 3, 'c': 1})c = c1 - c2 # keeps only +ve count elementsprint(c) # Counter({'a': 1, 'b': 1})c = c1 & c2 # intersection min(c1[x], c2[x])print(c) # Counter({'a': 1})c = c1 | c2 # union max(c1[x], c2[x])print(c) # Counter({'a': 2, 'c': 2})

Miscellaneous Operations on Python Counter

Let’s look at some code snippets for miscellaneous operations we can perform on Counter objects.

counter = Counter({'a': 3, 'b': 3, 'c': 0})# miscellaneous examplesprint(sum(counter.values())) # 6print(list(counter)) # ['a', 'b', 'c']print(set(counter)) # {'a', 'b', 'c'}print(dict(counter)) # {'a': 3, 'b': 3, 'c': 0}print(counter.items()) # dict_items([('a', 3), ('b', 3), ('c', 0)])# remove 0 or negative count elementscounter = Counter(a=2, b=3, c=-1, d=0)counter = +counterprint(counter) # Counter({'b': 3, 'a': 2})# clear all elementscounter.clear()print(counter) # Counter()

That’s all for Python Counter class.

You can download the complete example code from my GitHub Repository.

Reference: Python Docs

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Python Counter - Python Collections Counter | DigitalOcean (2024)
Top Articles
XRP Ledger Payments Now Supported by This Leading E-Commerce Platform: Details
Keep Cargo in Perfect Condition: Guaranteed Solution!
Uhauldealer.com Login Page
Dte Outage Map Woodhaven
Metallica - Blackened Lyrics Meaning
Weeminuche Smoke Signal
Missed Connections Inland Empire
Stadium Seats Near Me
Craigslist Mpls Mn Apartments
Craigslist Furniture Bedroom Set
Jessica Renee Johnson Update 2023
Es.cvs.com/Otchs/Devoted
The Connecticut Daily Lottery Hub
Hartland Liquidation Oconomowoc
Darksteel Plate Deepwoken
Lima Funeral Home Bristol Ri Obituaries
Nyuonsite
Pizza Hut In Dinuba
Spider-Man: Across The Spider-Verse Showtimes Near Marcus Bay Park Cinema
Jayah And Kimora Phone Number
Mikayla Campinos Laek: The Rising Star Of Social Media
Busted Campbell County
Beverage Lyons Funeral Home Obituaries
Bible Gateway passage: Revelation 3 - New Living Translation
Euro Style Scrub Caps
How to Grow and Care for Four O'Clock Plants
Zillow Group Stock Price | ZG Stock Quote, News, and History | Markets Insider
Scheuren maar: Ford Sierra Cosworth naar de veiling
Living Shard Calamity
Lbrands Login Aces
Fridley Tsa Precheck
In Branch Chase Atm Near Me
Newsday Brains Only
Composite Function Calculator + Online Solver With Free Steps
Where Do They Sell Menudo Near Me
El agente nocturno, actores y personajes: quién es quién en la serie de Netflix The Night Agent | MAG | EL COMERCIO PERÚ
Great Clips On Alameda
Craigslist Neworleans
Junee Warehouse | Imamother
Trap Candy Strain Leafly
2007 Peterbilt 387 Fuse Box Diagram
Andrew Lee Torres
Ethan Cutkosky co*ck
Kjccc Sports
Vci Classified Paducah
Mountainstar Mychart Login
Verizon Forum Gac Family
Ewwwww Gif
Charlotte North Carolina Craigslist Pets
Uncle Pete's Wheeling Wv Menu
Haunted Mansion Showtimes Near The Grand 14 - Ambassador
Yoshidakins
Latest Posts
Article information

Author: Stevie Stamm

Last Updated:

Views: 6366

Rating: 5 / 5 (60 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Stevie Stamm

Birthday: 1996-06-22

Address: Apt. 419 4200 Sipes Estate, East Delmerview, WY 05617

Phone: +342332224300

Job: Future Advertising Analyst

Hobby: Leather crafting, Puzzles, Leather crafting, scrapbook, Urban exploration, Cabaret, Skateboarding

Introduction: My name is Stevie Stamm, I am a colorful, sparkling, splendid, vast, open, hilarious, tender person who loves writing and wants to share my knowledge and understanding with you.