Python
list counting
duplicates
programming
coding tips

Python - Count elements in list

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

To count elements in a Python list, use len(lst) for total count, lst.count(x) for occurrences of a specific element, or collections.Counter(lst) for a frequency dictionary of all elements. Counter is the most versatile — it gives you the count of every unique element in a single pass, supports arithmetic operations, and provides methods like most_common(). For pandas DataFrames, use value_counts().

Total Count with len()

python
1items = [1, 2, 3, 4, 5]
2print(len(items))  # 5
3
4# Works with any iterable after conversion
5print(len(list(range(100))))  # 100

Count Specific Element with list.count()

python
1colors = ["red", "blue", "red", "green", "red", "blue"]
2
3print(colors.count("red"))    # 3
4print(colors.count("blue"))   # 2
5print(colors.count("yellow")) # 0
6
7# Count in nested structures
8matrix = [[1, 2], [1, 3], [1, 2]]
9print(matrix.count([1, 2]))  # 2

list.count() scans the entire list each time — O(n) per call. If you need counts for multiple elements, use Counter instead.

collections.Counter (Best for Frequency Counting)

python
1from collections import Counter
2
3words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
4counts = Counter(words)
5
6print(counts)
7# Counter({'apple': 3, 'banana': 2, 'cherry': 1})
8
9print(counts["apple"])    # 3
10print(counts["missing"])  # 0 (no KeyError)
11
12# Most common elements
13print(counts.most_common(2))
14# [('apple', 3), ('banana', 2)]
15
16# Least common
17print(counts.most_common()[-1])
18# ('cherry', 1)

Counter Arithmetic

python
1from collections import Counter
2
3basket1 = Counter(["apple", "apple", "banana"])
4basket2 = Counter(["apple", "banana", "cherry"])
5
6# Addition — combine counts
7print(basket1 + basket2)
8# Counter({'apple': 3, 'banana': 2, 'cherry': 1})
9
10# Subtraction — remove counts (drops zero and negative)
11print(basket1 - basket2)
12# Counter({'apple': 1})
13
14# Intersection — minimum of corresponding counts
15print(basket1 & basket2)
16# Counter({'apple': 1, 'banana': 1})
17
18# Union — maximum of corresponding counts
19print(basket1 | basket2)
20# Counter({'apple': 2, 'banana': 1, 'cherry': 1})

Dictionary Comprehension Approach

python
1items = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
2
3# Manual frequency dictionary
4freq = {}
5for item in items:
6    freq[item] = freq.get(item, 0) + 1
7print(freq)  # {1: 1, 2: 2, 3: 3, 4: 4}
8
9# Using defaultdict
10from collections import defaultdict
11freq = defaultdict(int)
12for item in items:
13    freq[item] += 1
14print(dict(freq))  # {1: 1, 2: 2, 3: 3, 4: 4}

These are equivalent to Counter but require more code. Use Counter unless you need custom logic during counting.

Counting with Conditions

python
1numbers = [1, -2, 3, -4, 5, -6, 7, 8, -9, 10]
2
3# Count positives
4positives = sum(1 for x in numbers if x > 0)
5print(positives)  # 6
6
7# Count using len + filter
8negatives = len([x for x in numbers if x < 0])
9print(negatives)  # 4
10
11# Count truthy values
12mixed = [0, 1, "", "hello", None, True, [], [1]]
13truthy_count = sum(1 for x in mixed if x)
14print(truthy_count)  # 4
15
16# Count by predicate with a function
17from collections import Counter
18
19def categorize(n):
20    if n > 0: return "positive"
21    if n < 0: return "negative"
22    return "zero"
23
24categories = Counter(categorize(n) for n in numbers)
25print(categories)  # Counter({'positive': 6, 'negative': 4})

Counting in Strings

python
1text = "hello world"
2
3# Character frequency
4from collections import Counter
5char_counts = Counter(text)
6print(char_counts.most_common(3))
7# [('l', 3), ('o', 2), ('h', 1)]
8
9# Count specific substring
10print(text.count("l"))   # 3
11print(text.count("lo"))  # 1
12
13# Word frequency
14words = "the cat sat on the mat the cat".split()
15word_counts = Counter(words)
16print(word_counts)
17# Counter({'the': 3, 'cat': 2, 'sat': 1, 'on': 1, 'mat': 1})

Common Pitfalls

  • Using list.count() in a loop for all elements: for x in items: counts[x] = items.count(x) is O(n^2) because count() scans the full list for each element. Use Counter(items) for O(n) frequency counting of all elements in a single pass.
  • Expecting Counter to raise KeyError for missing keys: Counter returns 0 for missing keys, not a KeyError. This is convenient but can mask typos: counts["aplpe"] silently returns 0 instead of signaling an error. Verify key names if counts seem unexpectedly zero.
  • Confusing len() with count(): len(lst) returns the total number of elements. lst.count(x) returns how many times x appears. Using the wrong one gives meaningless results — len() for "how many items total," count() for "how many of this specific item."
  • Modifying a list while counting: Inserting or removing elements during iteration changes the counts. Build the counter from the original list first, then modify. Counter takes a snapshot — subsequent list changes do not update the counter.
  • Using Counter on unhashable elements: Counter requires hashable elements (strings, numbers, tuples). Passing a list of lists raises TypeError: unhashable type: 'list'. Convert inner lists to tuples first: Counter(tuple(x) for x in nested_list).

Summary

  • Use len(lst) for total element count, lst.count(x) for a single element's frequency
  • Use collections.Counter for efficient frequency counting of all elements in one pass
  • Counter.most_common(n) returns the n most frequent elements as a sorted list
  • Use sum(1 for x in lst if condition) to count elements matching a predicate
  • Avoid list.count() inside loops — it causes O(n^2) performance; prefer Counter

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.