Python collections Counter: Count Items Easily
In this article
Use collections.Counter when you need to count how many times each item appears in a list, string, or other iterable. It is a dictionary subclass that stores items as keys and their counts as values, and it provides handy methods like most_common() and elements(). All you need is Python 3 (Counter is in the standard library, so no installation is required).
What You'll Need
- Python 3 installed (any recent version; Counter has been in the standard library since Python 2.7, but Python 3 is recommended).
- A text editor or IDE to write and run your code.
- Basic familiarity with Python dictionaries and lists.
Step-by-Step
- Import Counter from the collections module. At the top of your script, write:
from collections import Counter. You can also useimport collectionsand then refer tocollections.Counter, but the direct import is shorter. - Create a Counter from an iterable. Pass any iterable (list, tuple, string, etc.) to
Counter(). For example:c = Counter(['apple', 'banana', 'apple', 'orange', 'banana', 'apple']). The resulting Counter will have counts: apple: 3, banana: 2, orange: 1. You can also count characters in a string:Counter('hello')givesCounter({'l': 2, 'h': 1, 'e': 1, 'o': 1}). - Create an empty Counter and update it. Start with
c = Counter()and then callc.update(iterable)to add counts from an iterable, orc.update(mapping)to add counts from another dictionary/Counter. You can also manually set counts:c['apple'] += 1. - Access counts like a dictionary. Use square brackets:
c['apple']returns 3. If the key is missing, it returns 0 instead of raising a KeyError. To get a list of all unique items, uselist(c.keys())or simply iterate overc. - Find the most common items. Use
c.most_common(n)to get a list of the n most common elements and their counts, sorted from most to least. If you omit n, it returns all items sorted. For example,c.most_common(1)returns[('apple', 3)]. - Expand counts back into elements. Use
list(c.elements())to get an iterator over the elements repeated according to their counts. This is useful for reconstructing the original multiset. Note that elements with count <= 0 are ignored. - Combine or subtract Counters. You can add two Counters with
c1 + c2(counts are added), subtract withc1 - c2(counts are subtracted, but only positive counts remain), or usec1 & c2for intersection (minimum of counts) andc1 | c2for union (maximum of counts). These operations return new Counter objects. - Remove items with zero or negative counts. After subtraction, some counts may become zero or negative. To remove them, use
c += Counter()(which keeps only positive counts) ordel c[item]to delete a specific key. You can also usec.subtract()which allows negative counts, then clean up with+c(unary plus) to keep only positive counts. - Use Counter with other data types. Counter works with any hashable elements, including tuples, numbers, and custom objects (as long as they are hashable). For example, counting words in a list of strings is straightforward.
Common Mistakes
- Forgetting that missing keys return 0. Unlike a regular dictionary, accessing a missing key in a Counter does not raise a KeyError; it returns 0. This is usually helpful, but it can hide typos.
- Assuming Counter preserves insertion order. In Python 3.7+, Counter inherits from dict and thus maintains insertion order, but the order of
most_common()is by count, not insertion. - Using unhashable elements. You cannot count lists or dictionaries because they are unhashable. Convert them to tuples or strings first.
- Misunderstanding subtraction. The
-operator removes items with zero or negative counts, whilesubtract()keeps them. Know which one you need. - Modifying a Counter while iterating. Like dictionaries, changing a Counter's size during iteration can cause a RuntimeError. Iterate over a copy (e.g.,
list(c.items())) if you need to modify.
Tips
- Use
Counterfor quick frequency analysis; it's often faster and cleaner than manual loops with dictionaries. - When counting words, consider normalizing case and stripping punctuation first to avoid counting 'Apple' and 'apple' separately.
- For large datasets,
most_common()without an argument sorts all items, which can be slow; specify n if you only need the top few. - You can initialize a Counter with a dictionary or keyword arguments:
Counter({'a': 2, 'b': 1})orCounter(a=2, b=1). - Remember that Counter is a subclass of dict, so all regular dictionary methods (like
get,items,values) are available.
Troubleshooting
- Counter not found: Ensure you imported it correctly:
from collections import Counter. If you seeNameError: name 'Counter' is not defined, you likely forgot the import. - Unexpected counts: Check that your iterable contains hashable items and that you are not accidentally counting characters of a string when you meant words. Use
split()for words. - Negative counts after subtraction: Use
c += Counter()to remove non-positive counts, or use the-operator instead ofsubtract(). - TypeError: unhashable type: You are trying to count lists or dicts. Convert them to tuples or use a different approach.
- most_common returns unexpected order: Ties are broken by insertion order (in Python 3.7+). If you need a specific tie-breaker, sort the items manually.
Frequently Asked Questions
What is the difference between Counter and a regular dictionary?
Counter is a dict subclass designed for counting. It provides methods like most_common() and elements(), and missing keys return 0 instead of raising KeyError.
Can I use Counter with unhashable items like lists?
No, Counter requires hashable elements. Convert lists to tuples or strings before counting.
How do I get the count of a specific item?
Use square bracket notation: c['item']. If the item is not present, it returns 0.
What does most_common(n) return?
It returns a list of the n most common elements and their counts, sorted from most to least common. If n is omitted, it returns all items sorted.
Can I add or subtract Counters?
Yes, you can use + and - operators to combine Counters. The - operator keeps only positive counts, while subtract() allows negative counts.
Is Counter available in Python 2?
Yes, Counter was added in Python 2.7, but Python 3 is recommended for new code.