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()

'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

from collections import Counter

# Count the elements in a list.
fruits = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']
c = Counter(fruits)
print(c)  # Outputs: Counter({'apple': 3, 'banana': 2, 'cherry': 1})

# Access the count for each element like a dictionary.
print(c['apple'])   # Outputs: 3
print(c['grape'])   # 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: [('apple', 3), ('banana', 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_fruits = ['apple', 'grape', 'grape']
c.update(more_fruits)
print(c['apple'])  # Outputs: 4
print(c['grape'])  # 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']

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 .