How to Count Occurrences in Python List?

After spending years teaching Python at coding boot camps across California and working with data analysis teams at tech companies, I can tell you that counting occurrences in Python can be one of the fundamental skills that every programmer should know. In this comprehensive guide, I will walk you through seven different methods to count occurrences in Python list.

Count Occurrences in Python List

Let us learn some important methods to count occurrences in Python list.

Read How to Reverse a List in Python?

Method 1: Use the count() Method

The most simple way to count occurrences in a Python list is by using the built-in count() method. This method is part of Python’s list object and requires minimal code.

fruits = ["apple", "banana", "apple", "orange", "apple", "pear"]

# Counting occurrences of "apple"
apple_count = fruits.count("apple")
print(f"Number of apples: {apple_count}") 

Output:

Number of apples: 3

You can refer to the screenshot below to see the output.

How to Count Occurrences in Python List

The count() method is perfect for quickly finding how many times a specific element appears in your list. It’s simple, simple, and built into Python, making it my go-to method for basic counting tasks.

Check out How to Convert a List to a String in Python?

Method 2: Use a For Loop

While the count() method is convenient, sometimes you need more control over the counting process. A manual approach using a for loop gives you that flexibility:

scores = [85, 90, 85, 70, 85, 95, 90]

# Initialize a counter
count = 0

# Iterate through the list
for score in scores:
    if score == 85:
        count += 1

print(f"The score 85 appears {count} times") 

Output:

The score 85 appears 3 times

You can refer to the screenshot below to see the output.

python count occurrences in list

This approach might seem verbose compared to count() but it gives you the freedom to add additional logic or conditions during the counting process.

Read How to Remove the Last Element from a List in Python?

Method 3: Use the collections.Counter Class

For more advanced counting scenarios, the Counter class from Python’s collections module is a useful tool. It creates a dictionary-like object where keys are the elements from your list, and values are their counts:

from collections import Counter

colors = ["blue", "red", "blue", "green", "blue", "red"]

# Create a Counter object
color_counts = Counter(colors)

# Get count of a specific color
print(f"Number of blue: {color_counts['blue']}") 

# View all counts
print(color_counts) 
# Find the most common item
most_common_color, its_count = color_counts.most_common(1)[0]
print(f"The most common color is {most_common_color} with {its_count} occurrences")

Output:

Number of blue: 3
Counter({'blue': 3, 'red': 2, 'green': 1})
The most common color is blue with 3 occurrences

You can refer to the screenshot below to see the output.

python list count occurrences

The Counter class automatically counts all unique items in your list, saving you from writing multiple count() calls or complex loops.

Check out How to Flatten a List of Lists in Python?

Method 4: Use list Comprehension with sum()

List comprehensions combined with the sum() function offer an elegant way to count occurrences:

states = ["California", "Texas", "Florida", "California", "New York", "California"]

# Count occurrences using list comprehension
california_count = sum(1 for state in states if state == "California")
print(f"California appears {california_count} times")  # Output: California appears 3 times

This approach is concise and can be more readable for those familiar with Python’s functional programming features.

Read How to Sort a List of Tuples in Python?

Method 5: Use Dictionary Comprehension

For counting all elements at once, dictionary comprehensions provide another elegant approach:

animals = ["dog", "cat", "bird", "dog", "bird", "bird", "cat"]

# Count all occurrences using dictionary comprehension
animal_counts = {animal: animals.count(animal) for animal in set(animals)}
print(animal_counts)  # Output: {'dog': 2, 'cat': 2, 'bird': 3}

This creates a dictionary with each unique element as a key and its count as the value. However, note that this method calls count() for each unique element, which can be inefficient for very large lists.

Method 6: Use NumPy for Numerical Lists

When working with numerical data, NumPy can provide significant performance benefits:

import numpy as np

temperatures = [72, 75, 72, 78, 75, 72, 80, 75]
temp_array = np.array(temperatures)

# Count occurrences of value 72
count_72 = np.count_nonzero(temp_array == 72)
print(f"Temperature 72°F appears {count_72} times")  # Output: Temperature 72°F appears 3 times

# Get all unique values and their counts
unique_temps, counts = np.unique(temp_array, return_counts=True)
temp_count_dict = dict(zip(unique_temps, counts))
print(temp_count_dict)  # Output: {72: 3, 75: 3, 78: 1, 80: 1}

For large numerical datasets, NumPy’s vectorized operations can be significantly faster than Python’s built-in methods.

Check out How to Find the Length of a List in Python?

Method 7: Use defaultdict from Collections

The defaultdict class provides another efficient way to count occurrences:

from collections import defaultdict

cities = ["New York", "Chicago", "Los Angeles", "Chicago", "New York", "New York"]

# Create a defaultdict with int as the default factory
city_counts = defaultdict(int)

# Count occurrences
for city in cities:
    city_counts[city] += 1

print(dict(city_counts))  # Output: {'New York': 3, 'Chicago': 2, 'Los Angeles': 1}

The advantage of defaultdict is that it automatically initializes new keys with a default value (in this case, 0 for int), so you don’t need to check if a key exists before incrementing its count.

Read How to Get the Last Element of a List in Python?

Performance Comparison

Let’s compare the performance of these methods for counting occurrences in a list:

MethodSmall ListsLarge ListsCode ComplexityFlexibility
count() MethodFastSlow for multiple itemsLowLow
For LoopMediumMediumMediumHigh
collections.CounterMediumFastLowHigh
List ComprehensionMediumMediumMediumMedium
Dictionary ComprehensionFastSlowMediumMedium
NumPySlow (overhead)Very FastMediumMedium
defaultdictMediumFastMediumHigh

Applications

Let us understand more by considering some real-world examples.

  • Data Analysis: Finding the most frequent values in customer data
  • Text Processing: Counting word frequencies in documents
  • Market Research: Analyzing survey responses
  • Machine Learning: Creating feature vectors from categorical data
  • Quality Control: Identifying recurring issues in reports

Best Practices and Tips

After years of teaching Python. I have developed these best practices for counting list occurrences:

1. Choose the Right Method for Your Use Case:

  • For simple one-off counts, use list.count()
  • For counting all elements at once, use Counter
  • For performance-critical numerical data, use NumPy

2. Consider Data Size:

  • Methods like Counter and defaultdict scale better for large datasets
  • Calling count() repeatedly in a loop or comprehension can be slow for large lists

3. Be Mindful of Case Sensitivity:

  • Remember that “Apple” and “apple” are different items in a list
  • Use .lower() or .upper() for case-insensitive counting if needed

4. Handle Special Cases:

  • Be careful when counting objects or custom classes (ensure they implement proper equality comparison)
  • Consider using collections.Counter with a custom counting function for complex objects

Check out How to Split a List in Python?

Conclusion

In this article, I explained how to count occurrences in Python list. I discussed seven important methods to accomplish this task such as using count() method, using for loop, using collections.Counter class, using list comprehension with sum(), using dictionary comprehension, using Numpy for numerical lists, and defaultdict from collections.

You can also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.