python
programming
data-analysis
algorithms
lists

How to count the frequency of the elements in an unordered list?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Counting how often each value appears in a Python list is a common task in data cleaning, reporting, and interview problems. The standard solution is collections.Counter, but understanding the manual dictionary pattern is also useful when you need custom behavior.

Use Counter for the Usual Case

Counter is part of the standard library and is designed for frequency counting. It consumes an iterable and returns a mapping from value to count.

python
1from collections import Counter
2
3items = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
4counts = Counter(items)
5
6print(counts)
7print(counts['apple'])
8print(counts.most_common(2))

This is usually the best answer because the intent is obvious and the code is short. It also gives you useful helpers such as most_common, which saves you from writing separate sorting logic.

Convert the Result When You Need Plain Dictionaries

Counter is a specialized dictionary subclass. If the next step in your code wants a plain dict, convert it explicitly.

python
1from collections import Counter
2
3items = ['red', 'blue', 'red', 'green']
4counts = dict(Counter(items))
5print(counts)

That conversion is cheap and makes the return type obvious when you are passing the result to APIs that expect a normal dictionary.

Build Counts Manually to Understand the Pattern

A manual loop shows the underlying algorithm clearly. It is also useful when you need custom counting rules, such as ignoring certain elements or normalizing values before incrementing.

python
1items = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
2counts = {}
3
4for item in items:
5    counts[item] = counts.get(item, 0) + 1
6
7print(counts)

This solution performs one pass through the list and updates the count associated with each value. It is simple, readable, and efficient enough for most practical use.

Normalize Values Before Counting

Real input is often messy. If 'Apple', 'apple', and ' apple ' should be treated as the same value, normalize first.

python
1from collections import Counter
2
3raw_items = ['Apple', ' apple ', 'BANANA', 'banana', 'Apple']
4normalized = [item.strip().lower() for item in raw_items]
5counts = Counter(normalized)
6
7print(counts)

Doing normalization before counting is usually cleaner than trying to merge categories later.

Watch the Difference Between One-Off Checks and Full Frequency Tables

Python lists also have a count method.

python
items = ['apple', 'banana', 'apple', 'orange']
print(items.count('apple'))

This is fine when you care about one known value. It is a poor fit when you want counts for every distinct value, because repeated calls scan the list again and again. For a full frequency table, Counter or a single dictionary loop is the right model.

Handle Unhashable Elements Deliberately

Dictionary-style counting requires hashable keys. Strings, numbers, and tuples are fine. Lists and dictionaries are not. If your elements are unhashable, convert them into a hashable representation first.

python
1from collections import Counter
2
3rows = [[1, 2], [1, 2], [3, 4]]
4counts = Counter(tuple(row) for row in rows)
5print(counts)

This is a common fix when counting structured records that arrive as lists.

Common Pitfalls

One common mistake is using items.count(value) repeatedly for every distinct item. That works, but it rescans the input many times and becomes unnecessarily slow as the list grows.

Another problem is forgetting to normalize input before counting. If casing and whitespace are inconsistent, the counts may reflect formatting differences instead of meaningful categories.

It is also easy to overlook hashability. If your elements are mutable containers such as lists, Counter and dictionaries cannot use them directly as keys.

Summary

  • Use collections.Counter when you want the clearest built-in solution.
  • Use a dictionary loop when you need custom counting logic.
  • Normalize data before counting if logically equivalent values have different formatting.
  • Use list.count(...) only for isolated one-value checks.
  • Convert unhashable data into a hashable form before using it as a frequency key.

Course illustration
Course illustration

All Rights Reserved.