Counter in Python: Syntax, Methods and 8 Examples

If you have a list or string and you want to count each item, a Counter in Python is the quickest way to get it. It takes any iterable and gives you back each item with its count, in a dict subclass from collections.

from collections import Counter
print(Counter(["NY", "CA", "NY", "TX", "NY"]))
# Counter({'NY': 3, 'CA': 1, 'TX': 1})

In this tutorial, I’ll go through eight Counter examples, from plain lists and word counts to most_common(), missing keys, update() and subtract(), counter math, total() and a duplicate check. Every output comes from Python 3.12.5 in Command Prompt.

Python collections.Counter() Syntax

class collections.Counter(**kwargs)
class collections.Counter(iterable, /, **kwargs)
class collections.Counter(mapping, /, **kwargs)

Import it with from collections import Counter. It’s part of the Python standard library, so there’s nothing to install.

ParameterRequiredDefaultDescription
iterableNo–A list, string, tuple or generator of hashable items to count
mappingNo–A dict or Counter of item: count pairs to start from
**kwargsNo–Counts as keyword arguments, like Counter(adult=3, child=2)

Return value: a Counter object that maps each element to an integer count. Call it with no arguments and you get an empty Counter() you can fill later.

Because it’s a subclass of the Python dict() type, keys(), values(), items() and get() all work. A missing key returns 0 instead of raising KeyError.

Note: Counter has been in Python since 3.1. The total() method and comparisons like <= need Python 3.10 or newer.

When to Use Counter in Python

  • Tallying votes, survey answers or order items
  • Finding the most frequent words, cities or products
  • Spotting duplicate IDs in a list
  • Tracking stock levels that go up and down
  • Comparing two collections item by item, like anagrams or inventory snapshots

Counters in Python replace the classic loop that builds a dict and adds 1 for each item. If you only need to order a plain dict by its numbers, see how to sort a dictionary by value in Python.

Example 1: Count Items in a List with Counter

Let me start with the drink orders from one morning at a coffee cart:

from collections import Counter

orders = ["latte", "mocha", "latte", "cold brew",
          "latte", "mocha", "espresso"]

counts = Counter(orders)
print(counts)
print(counts["latte"])
print(dict(counts))

Output:

Counter({'latte': 3, 'mocha': 2, 'cold brew': 1, 'espresso': 1})
3
{'latte': 3, 'mocha': 2, 'cold brew': 1, 'espresso': 1}
Counter in Python counting coffee orders in a list, one count and a dict conversion in Command Prompt
Counter tallies a list in one call.

How does this work? Counter turned seven orders into four drinks: latte 3, mocha 2 and one each for cold brew and espresso. counts["latte"] read one count like a dict lookup, and dict(counts) made a plain dictionary.

Pro Tip: pass the whole list at once. It’s shorter and easier to read than writing counts[item] += 1 in your own loop.

Example 2: Count Characters and Words in a Python String

A string is an iterable of characters, so Counter counts letters by default. To count words, split the text first:

from collections import Counter

print(Counter("mississippi"))

review = "Fast shipping. Great price. Fast support, great packaging."
words = review.lower().replace(".", "").replace(",", "").split()
print(Counter(words))

Output:

Counter({'i': 4, 's': 4, 'p': 2, 'm': 1})
Counter({'fast': 2, 'great': 2, 'shipping': 1, 'price': 1, 'support': 1, 'packaging': 1})

How does this work? “mississippi” has four i’s, four s’s, two p’s and one m. For the review, I lowercased the text and stripped periods and commas before split(), so “Fast” and “fast” landed in the same bucket.

For more letter-counting options, see counting characters in a Python string. To do this for a whole text file, check how to count words in a file with Python.

Example 3: Find the Most Common Items with most_common()

most_common(n) returns the n highest counts as (item, count) tuples. Here are 10 online orders by shipping city:

from collections import Counter

order_cities = ["Austin", "Denver", "Austin", "Boston", "Denver",
                "Austin", "Seattle", "Boston", "Denver", "Miami"]

city_counts = Counter(order_cities)
print(city_counts.most_common(3))
print(city_counts.most_common(1)[0][0])
print(city_counts.most_common()[-1])
print(list(city_counts))

Output:

[('Austin', 3), ('Denver', 3), ('Boston', 2)]
Austin
('Miami', 1)
['Austin', 'Denver', 'Boston', 'Seattle', 'Miami']
Python Counter most_common method listing the top shipping cities and the least common city in Command Prompt
most_common() sorts by count; ties keep first-seen order.

How does this work? Austin and Denver both had 3 orders, and Austin came first because it showed up first in the list. most_common(1)[0][0] pulled out just the top city, and most_common()[-1] gave the least common one.

Looking for an ordered counter in Python? Since Python 3.7, a Counter remembers insertion order, which is why list(city_counts) followed the original list. When printed, it’s shown highest count first, and most_common() returns that sorted order.

You can also feed Counter a generator expression, so you don’t need a temporary list. Here I count file types in a folder listing and draw a quick text bar chart:

from collections import Counter

files = ["report.pdf", "q4.xlsx", "logo.png", "notes.txt",
         "invoice.pdf", "photo.png", "budget.xlsx", "contract.pdf"]

by_type = Counter(name.rsplit(".", 1)[-1] for name in files)
for ext, n in by_type.most_common():
    print(f"{ext:<5} {'#' * n}  {n}")

Output:

pdf   ###  3
xlsx  ##  2
png   ##  2
txt   #  1

How does this work? The generator pulled the extension after the last dot, and Counter tallied 3 PDFs, 2 spreadsheets, 2 PNGs and 1 text file. most_common() then fed the bars from biggest to smallest.

Example 4: Access Counts, Missing Keys and elements() in Python

You can build a Counter three ways: from an iterable, from a dict like Counter({"adult": 3}), or from keyword arguments. Counter behaves like a dict with one friendly twist. Here’s a ticket order built from keyword arguments:

from collections import Counter

tickets = Counter(adult=3, child=2, senior=0)

print(tickets["student"])
print("student" in tickets)
print(list(tickets.elements()))

print(len(tickets))
del tickets["senior"]
print(len(tickets), tickets)

Output:

0
False
['adult', 'adult', 'adult', 'child', 'child']
3
2 Counter({'adult': 3, 'child': 2})

How does this work? Asking for “student” returned 0, not a KeyError, and didn’t add the key. elements() repeated each ticket by its count and skipped senior, which was 0.

Setting a count to 0 kept the key, so the length was still 3. Only del removed it, which dropped the length to 2.

That 0 default is the big difference from a regular dict, where a missing key crashes your script. See how to fix a KeyError in a Python dictionary for the plain-dict side.

Example 5: Update and Subtract Counts in a Counter

update() adds counts instead of replacing them, and subtract() takes them away. Let me run a small store’s inventory:

from collections import Counter

inventory = Counter({"hoodie": 20, "t-shirt": 35, "cap": 8})

inventory.update({"hoodie": 10})
inventory.update(["cap", "cap"])
print(inventory)

inventory.subtract({"t-shirt": 12, "cap": 15})
print(inventory)

Output:

Counter({'t-shirt': 35, 'hoodie': 30, 'cap': 10})
Counter({'hoodie': 30, 't-shirt': 23, 'cap': -5})
Python Counter update and subtract methods changing store inventory, with a negative cap count in Command Prompt
update() adds, subtract() can go negative.

How does this work? The restock took hoodies from 20 to 30, and the two “cap” strings added 2 caps. Then subtract() sold 12 t-shirts and 15 caps, so caps dropped to -5, a quick flag that you oversold.

A normal dict’s update() overwrites values instead. Compare it with the Python dictionary update() method.

Pro Tip: subtract() keeps zero and negative counts. Use +inventory when you only want items still in stock.

Example 6: Add, Subtract and Combine Counters with Math Operators

Counters support +, -, & and |, which makes week-over-week comparisons easy. Here are two weeks of coffee sales:

from collections import Counter

week1 = Counter(latte=40, mocha=25, tea=10)
week2 = Counter(latte=35, mocha=30, cold_brew=12)

print(week1 + week2)
print(week1 - week2)
print(week1 & week2)
print(week1 | week2)
print(+Counter(latte=3, mocha=0, tea=-2))

Output:

Counter({'latte': 75, 'mocha': 55, 'cold_brew': 12, 'tea': 10})
Counter({'tea': 10, 'latte': 5})
Counter({'latte': 35, 'mocha': 25})
Counter({'latte': 40, 'mocha': 30, 'cold_brew': 12, 'tea': 10})
Counter({'latte': 3})
Python Counter addition, subtraction, intersection, union and unary plus on two weeks of sales in Command Prompt
Counter math drops anything at 0 or below.

How does this work? + added the weeks, so lattes hit 75. - kept only positive leftovers: tea (10) and latte (5) stayed, while mocha (-5) disappeared.

& took the smaller count of each item and | took the larger one. Unary + dropped the zero and negative counts, leaving only latte.

Keep the difference in mind: the - operator throws away anything at 0 or below, while subtract() keeps it.

Example 7: Get the Total Count with total() in Python 3.10+

total() adds up every count. Here’s a city poll on a new park name, with each option’s share:

from collections import Counter

votes = Counter({"Riverside Park": 412, "Oak Commons": 389,
                 "Harbor Green": 145})

print(votes.total(), sum(votes.values()))
for name, n in votes.most_common():
    print(f"{name}: {n / votes.total():.1%}")

print(Counter(a=1) == Counter(a=1, b=0))
print(Counter({"Harbor Green": 100}) <= votes)

Output:

946 946
Riverside Park: 43.6%
Oak Commons: 41.1%
Harbor Green: 15.3%
True
True
Python Counter total method summing poll votes with percentage shares and comparison results in Command Prompt
total() matches sum() over the values.

How does this work? total() returned 946, the same as the Python sum() function over values(). The loop then printed each share in most_common() order.

Comparisons treat missing items as 0, so Counter(a=1) equals Counter(a=1, b=0). The <= check confirmed that 100 Harbor Green votes fit inside the poll.

On Python 3.9 or older, use sum(votes.values()) instead of total().

Example 8: Find Duplicates and Check Anagrams with Counter

Counter is handy for quick data checks. Let me find repeated invoice IDs and test three anagram pairs:

from collections import Counter

invoice_ids = ["INV-1001", "INV-1002", "INV-1001", "INV-1003",
               "INV-1002", "INV-1001"]
dupes = {inv: n for inv, n in Counter(invoice_ids).items() if n > 1}
print(dupes)

def is_anagram(a, b):
    clean = lambda s: s.replace(" ", "").lower()
    return Counter(clean(a)) == Counter(clean(b))

print(is_anagram("Listen", "Silent"))
print(is_anagram("Dormitory", "Dirty room"))
print(is_anagram("Apple", "Paper"))

Output:

{'INV-1001': 3, 'INV-1002': 2}
True
True
False
Python Counter finding duplicate invoice IDs and checking anagram pairs in Command Prompt
Duplicates and anagrams in a few lines.

How does this work? INV-1001 showed up 3 times and INV-1002 twice, so both landed in the dict. Two strings are anagrams when their letter counts match, so “Dormitory” and “Dirty room” passed once spaces and case were gone.

For other approaches, see how to find duplicates in a Python list and checking if a string is an anagram in Python.

Counter vs dict vs list.count(): Which Should You Use?

All three can count things in Python, but they fit different jobs:

ApproachBest forMissing itemWork done
Counter(items)Counting every itemReturns 0One pass over the data
dict + loopCustom counting rulesKeyError unless you use get()One pass, more code
list.count(x)Counting one known itemReturns 0A full scan on every call

My rule: use list.count() for a single value and Counter for everything else. For the one-item case, see counting occurrences of an item in a Python list, or counting occurrences in Python arrays for NumPy.

You may also see defaultdict(int) used for counting. It works, but you lose most_common(), total() and the math operators, so I reach for Counter first.

In pandas, Series.value_counts() does the same job for a DataFrame column. Here’s how to count unique values in a pandas column.

Common Mistakes with Python Counter

Here are six mistakes I see often, each from a real run:

from collections import Counter

tests = [lambda: Counter.fromkeys(["NY", "CA"]),
         lambda: Counter([["NY", "CA"], ["TX"]]),
         lambda: Counter(2026)]
for n, test in enumerate(tests, 1):
    try:
        test()
    except Exception as err:
        print(f"{n}. {type(err).__name__}: {err}")

print("4.", Counter("New York").most_common(2))
c = Counter()
c.update([("latte", 3)])
print("5.", c)
c = Counter(latte=1)
c["latte"] -= 1
print("6.", len(c), c)

Output:

1. NotImplementedError: Counter.fromkeys() is undefined.  Use Counter(iterable) instead.
2. TypeError: unhashable type: 'list'
3. TypeError: 'int' object is not iterable
4. [('N', 1), ('e', 1)]
5. Counter({('latte', 3): 1})
6. 1 Counter({'latte': 0})
Common Python Counter mistakes: fromkeys error, unhashable list, int not iterable, letters vs words, update pairs and zero counts in Command Prompt
Six Counter mistakes and what they print.
  1. Counter.fromkeys() raises NotImplementedError. Build it with Counter(iterable).
  2. Lists inside a list aren’t hashable. Convert each one to a tuple first.
  3. A number isn’t iterable. Wrap it in a list, or use str(2026) to count its digits.
  4. A string counts letters, not words. Call split() first.
  5. update() wants items, not (key, count) pairs. Pass a dict: c.update({"latte": 3}).
  6. Decrementing to 0 doesn’t remove the key. Use del or +c to clean up.

Wrapping Up the Python Counter Class

The Python Counter class turns counting into one line: pass an iterable, then read counts, call most_common() or do math on the results. A missing key gives 0, and total() adds everything up on 3.10+.

Next, browse more Python built-in functions and methods.

Keep going with these related tutorials:

Python Counter: Common Questions

How do I use Counter in Python?

Import it with from collections import Counter, pass a list or string, then read counts by key: Counter("banana")["a"] returns 3.

What does Counter do in Python?

It counts hashable items and stores them as item: count pairs, with extras like most_common(), elements(), update(), subtract() and total().

How do I sort a Counter by key?

Use sorted(c.items()). For Counter(b=2, a=5) it returned [('a', 5), ('b', 2)].

How do I convert a Counter to a dictionary or list?

dict(c) gives a plain dict like {'b': 2, 'a': 5}, and list(c.elements()) gives ['b', 'b', 'a', 'a', 'a', 'a', 'a'].

How do I reset a Counter?

Call c.clear(). The counter then prints as Counter().

Can a Counter hold zero or negative counts?

Yes. subtract() and direct assignment can store them, but the +, -, & and | operators drop anything at 0 or below. See collections.Counter in the Python docs.