Python Counter: count occurrences and words

Count list occurrences with Python Counter, separate words from characters, and understand result order, ties, missing keys and empty inputs.

PythonBy
Published on

You have a list with repeated values and need to know how often each one occurs. Counting one value and building a frequency table call for different tools.

In short

Use items.count(value) to count one specific value. For all frequencies, import Counter from collections and call Counter(items): each item becomes a key whose value is its occurrence count. To count words, pass a sequence of words, such as text.split(), rather than the text itself.

Should you use count or Counter for a list?

count returns an integer for the requested value. Counter builds a frequency table for every distinct value it encounters.

counts.py
from collections import Counter
items = ["b", "a", "b", "c", "a", "b"]print(items.count("b"))counts = Counter(items)print(dict(counts))print(list(counts.items()))print(counts.most_common(2))
Terminal
$ python3 counts.py3{'b': 3, 'a': 2, 'c': 1}[('b', 3), ('a', 2), ('c', 1)][('b', 3), ('a', 2)]

The number 3 answers “how many b values?”. The dictionary answers “how many of each value?”. dict(counts) produces an ordinary dictionary; counts.most_common(2) returns the two most frequent item/count pairs.

Calling items.count(item) for every item scans the list repeatedly, including repeated scans for duplicates. Build all frequencies in one counting pass instead. Keep count for a single value: a short question doesn't need a separate counting object.

How does the frequency table build up?

Each occurrence increases its own total. A dictionary loop lets you follow the process without an import.

loop.py
items = ["b", "a", "b"]counts = {}for item in items:    counts[item] = counts.get(item, 0) + 1    print(dict(counts))
Terminal
$ python3 loop.py{'b': 1}{'b': 1, 'a': 1}{'b': 2, 'a': 1}
Counting b, a, b

Step 1 of 3

First b

item
b
  1. b1
  2. aabsent

b appears for the first time.

Read all steps
  1. 1. First b

    item
    b
    1. b1
    2. aabsent

    b appears for the first time.

  2. 2. Then a

    item
    a
    1. b1
    2. a1

    A second key is created.

  3. 3. Second b

    item
    b
    1. b2occurrence added
    2. a1

    The count for b increases without moving its key.

The figure follows this loop's states. Counter handles the counting without requiring you to write the accumulation. The get(item, 0) pattern also helps when you're building values more complex than occurrence counts.

How do you count words instead of characters?

Split the text before counting. Passing a string directly to Counter counts individual characters.

words.py
from collections import Counter
text = "Row row Row\nrow!"print(dict(Counter(text.split())))print(dict(Counter("aba")))print(dict(Counter([])))print(dict(Counter(" \t\n".split())))
Terminal
$ python3 words.py{'Row': 2, 'row': 1, 'row!': 1}{'a': 2, 'b': 1}{}{}

Here, Row, row, and row! remain separate words. With no argument, split() groups whitespace and doesn't create empty words at either end. It also recognizes Unicode whitespace beyond the spaces, tabs, and newlines in this example. Tokenization is part of your definition of a word: this program isn't a linguistic parser.

Empty input produces an empty dictionary. There's no need for a special case before counting. For explicit separators and empty fields, see split and whitespace.

Python

tally_words

8-bit

Count words while preserving case, punctuation, and first appearance order. The contract defines the separators and expects an empty dictionary when the text contains no words.

Open the exercise

What order do the results use?

Iteration follows first appearance order; most_common() sorts by decreasing frequency. Ties follow the order in which the items first appeared.

updates.py
from collections import Counter
counts = Counter(["b", "a"])counts.update(["a", "b", "c"])print(dict(counts))print(counts.most_common())counts.update({"b": 3})print(dict(counts))
Terminal
$ python3 updates.py{'b': 2, 'a': 2, 'c': 1}[('b', 2), ('a', 2), ('c', 1)]{'b': 5, 'a': 2, 'c': 1}

After the first update, b and a both have a count of two. b remains ahead of a in both views. The next call adds three occurrences to b: update adds counts, unlike an ordinary dictionary update that replaces values. A mapping passed to the constructor or to update supplies existing counts; an iterable of words supplies occurrences to count.

This matters when combining batches. Use most_common(n) to display the most frequent items, or iterate over items() to keep arrival order. The dictionary order guide covers insertion and equality rules.

Does a missing key exist with a zero count?

Reading a missing key from a Counter returns zero without inserting the key. Assigning zero does create an entry.

missing.py
from collections import Counter
counts = Counter(["b", "a", "b"])print(counts["z"])print("z" in counts)counts["z"] = 0print("z" in counts)print(dict(counts))
Terminal
$ python3 missing.py0FalseTrue{'b': 2, 'a': 1, 'z': 0}

Membership checks stored keys rather than positive counts. If you modify counts, an in check alone doesn't mean “occurred at least once”. An ordinary dictionary keeps its usual behavior: a missing key can raise KeyError.

Which values can you count?

Items must work as dictionary keys, so lists won't do. For small rows of numbers, tuples can provide a hashable representation.

keys.py
from collections import Counter
try:    Counter([[1, 2], [1, 2]])except TypeError as error:    print(type(error).__name__)print(dict(Counter([(1, 2), (1, 2)])))print(dict(Counter([1, True, 1.0])))
Terminal
$ python3 keys.pyTypeError{(1, 2): 2}{1: 3}

Converting to a tuple isn't a universal fix: a tuple containing a list is still unhashable. Check the shape of your data before choosing a key.

The values 1, True, and 1.0 compare equal and share an entry. If your application must distinguish their types, define a key that includes that information; the counter won't make that decision for you.

Frequently asked questions

Do I need to install collections?

No. The module is part of Python's standard library.

Does Counter return a list?

No, it's a dictionary subclass. most_common() returns a list of pairs, while dict(counts) produces an ordinary dictionary.

Can I reuse a generator for two counts?

The first count consumes the generator's remaining items. Counting that same exhausted generator again yields an empty result; recreate the source to start over.

Sources

Now write it yourself.