Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Python Dictionary

  1. Home
  2. Python Dictionary
  3. collections.Counter()

collections.Counter()

Since: Python 2(2000)

'Counter' is a subclass of dict that counts the occurrences of elements in an iterable such as a list or string. It is useful for frequency analysis and ranking.

Syntax

from collections import Counter

# Create a Counter from an iterable.
c = Counter(iterable)

# Get the n most common elements.
c.most_common(n)

# Return an iterator that repeats each element by its count.
c.elements()

# Arithmetic operations on Counters
c1 + c2 # Add counts together.
c1 - c2 # Subtract counts (elements with zero or negative counts are excluded).
c1 & c2 # Keep the minimum count for each element.
c1 | c2 # Keep the maximum count for each element.

Methods and Operators

Method / OperatorDescription
Counter(iterable)Creates a dictionary from an iterable, with each element as a key and its occurrence count as the value.
c.most_common(n)Returns a list of the n most common elements as '[( element, count), ...]', sorted by count descending. Omitting n returns all elements.
c.elements()Returns an iterator that repeats each element by its count. Elements with a count less than one are not included.
c.update(iterable)Adds the counts from a new iterable to the existing Counter.
c.subtract(iterable)Subtracts the counts from a new iterable from the existing Counter. Negative values are preserved.
c1 + c2Returns a new Counter with counts added together from both Counters.
c1 - c2Returns a Counter with c2's counts subtracted from c1 (only positive values are kept).

Sample Code

collections_counter.py
from collections import Counter

# Count the elements in a list.
members = ['Okabe', 'Kurisu', 'Okabe', 'Mayuri', 'Kurisu', 'Okabe']
c = Counter(members)
print(c) # Outputs: Counter({'Okabe': 3, 'Kurisu': 2, 'Mayuri': 1})

# Access the count for each element like a dictionary.
print(c['Okabe']) # Outputs: 3
print(c['Suzuha']) # Returns 0 for a missing key (no KeyError).

# Use most_common() to get the top n most frequent elements.
print(c.most_common(2)) # Outputs: [('Okabe', 3), ('Kurisu', 2)]

# Count character frequencies in a string.
text = 'programming'
char_count = Counter(text)
print(char_count.most_common(3))
# Outputs the 3 most frequent characters (e.g., [('g', 2), ('r', 2), ('m', 2)]).

# Use update() to add more counts.
more_members = ['Okabe', 'Suzuha', 'Suzuha']
c.update(more_members)
print(c['Okabe']) # Outputs: 4
print(c['Suzuha']) # Outputs: 2

# Arithmetic operations on Counters
c1 = Counter({'a': 3, 'b': 2})
c2 = Counter({'a': 1, 'c': 4})
print(c1 + c2) # Outputs: Counter({'c': 4, 'a': 4, 'b': 2})
print(c1 - c2) # Outputs: Counter({'a': 2, 'b': 2}) (positive values only)
print(c1 & c2) # Outputs: Counter({'a': 1}) (minimum counts)
print(c1 | c2) # Outputs: Counter({'c': 4, 'a': 3, 'b': 2}) (maximum counts)

# Use elements() to expand elements by their counts.
print(sorted(c1.elements())) # Outputs: ['a', 'a', 'a', 'b', 'b']

Running the code produces the following output:

python3 collections_counter.py
Counter({'Okabe': 3, 'Kurisu': 2, 'Mayuri': 1})
3
0
[('Okabe', 3), ('Kurisu', 2)]
[('r', 2), ('g', 2), ('m', 2)]
4
2
Counter({'a': 4, 'c': 4, 'b': 2})
Counter({'a': 2, 'b': 2})
Counter({'a': 1})
Counter({'c': 4, 'a': 3, 'b': 2})
['a', 'a', 'a', 'b', 'b']

Common Mistakes

Common Mistake 1: Accessing a missing key

'Counter' returns '0' when you access a missing key (no 'KeyError' is raised). This behavior differs from a regular dictionary.

from collections import Counter

c = Counter({'Okabe Rintaro': 3, 'Makise Kurisu': 2})

# A missing key returns 0 — no KeyError
print(c['Shiina Mayuri']) # 0 (no error)
print(c.get('Shiina Mayuri')) # None (get() returns None)

# Deleting a key that held 0 may leave it in the counter
del c['Shiina Mayuri'] # del on a key that held 0 may not fully remove it

Common Mistake 2: Forgetting to pass an argument to most_common()

'most_common()' returns all elements when called without an argument. Pass a number when you only need the top N elements.

from collections import Counter

votes = Counter({'Okabe Rintaro': 45, 'Makise Kurisu': 38, 'Shiina Mayuri': 29,
                 'Hashida Itaru': 15, 'Amane Suzuha': 22})

# No argument: all elements (descending order)
print(votes.most_common())
# [('Okabe Rintaro', 45), ('Makise Kurisu', 38), ('Shiina Mayuri', 29), ...]

# Top 2 only
print(votes.most_common(2))
# [('Okabe Rintaro', 45), ('Makise Kurisu', 38)]

Common Mistake 3: Subtraction silently drops negative counts

When you subtract one 'Counter' from another with '-', elements with a result of zero or below are automatically removed. Use a regular dict operation if you need to preserve negative values.

from collections import Counter

before = Counter({'Okabe Rintaro': 5, 'Makise Kurisu': 3})
after = Counter({'Okabe Rintaro': 2, 'Makise Kurisu': 7})

# - operator: elements at or below zero are dropped
diff = before - after
print(diff) # Counter({'Okabe Rintaro': 3}) (Makise Kurisu's negative count is gone)

# subtract(): negative values are preserved
result = Counter(before)
result.subtract(after)
print(dict(result)) # {'Okabe Rintaro': 3, 'Makise Kurisu': -4}

Practical Patterns

Common patterns for text analysis, vote tallying, and inventory management.

from collections import Counter

# Count word frequency from text
text = 'Okabe Makise Okabe Mayuri Okabe Makise'
word_count = Counter(text.split())
print(word_count.most_common(2))
# [('Okabe', 3), ('Makise', 2)]

# Combine two Counters
morning = Counter({'Okabe Rintaro': 3, 'Makise Kurisu': 2})
evening = Counter({'Okabe Rintaro': 1, 'Shiina Mayuri': 4})
total = morning + evening
print(dict(total))
# {'Okabe Rintaro': 4, 'Makise Kurisu': 2, 'Shiina Mayuri': 4}

# Find the increase since the previous count
prev = Counter({'Okabe Rintaro': 5, 'Makise Kurisu': 3, 'Hashida Itaru': 2})
curr = Counter({'Okabe Rintaro': 8, 'Makise Kurisu': 3, 'Hashida Itaru': 4})
diff = curr - prev
print(dict(diff))
# {'Okabe Rintaro': 3, 'Hashida Itaru': 2}

Notes

Since 'Counter' is a subclass of dict, you can use all standard dictionary methods ('keys()', 'values()', 'items()', etc.) directly. Unlike a regular dictionary, accessing a missing key returns '0' instead of raising a 'KeyError'.

Counter makes it straightforward to write code that answers "how many times does each element appear?" — useful for survey tallying, text analysis, and log frequency analysis.

The subtraction operator ('-') between Counters excludes elements with zero or negative results, whereas the 'subtract()' method preserves negative values. Use whichever fits your needs.

For a dictionary with default values, see 'collections.defaultdict()'.

If you find any errors or copyright issues, please .