Python: Count Occurrences in Arrays and Lists (With Practical Examples)

When you work with real-world data in Python, a common task is to answer questions like: “How many times does this value appear?” Whether you are analyzing survey responses, counting events in logs, or preparing features for machine learning, you often need to count occurrences efficiently and correctly.

In this tutorial, you will learn several Pythonic ways to count occurrences in arrays and lists, understand when to use each method, and see how they behave on large datasets. You will also see realistic examples that mirror how data engineers, analysts, and ML practitioners actually work.

Arrays vs Lists in Python

In everyday Python code, especially for small to medium-sized tasks, most developers use lists to store sequences of values. A list is a flexible built-in container that can hold any object:

numbers = [1, 2, 3, 1, 2, 1]
states = ["California", "Texas", "New York", "California"]

For numeric and performance-critical workloads (for example, machine learning, scientific computing, or vectorized operations), you might use:

  • array objects from the standard library array module for basic numeric arrays
  • numpy.ndarray for fast, vectorized operations in data science and ML workflows

In this tutorial, we will:

  • Use lists for basic examples to keep concepts clear
  • Show how to apply the same ideas to array and NumPy arrays where it matters

Method 1: Use the list.count() Method

If you only need to count how many times a single value appears, the simplest approach is the built-in list.count() method.

# Example: Counting occurrences in a list
states = ["California", "Texas", "New York", "California", "Texas", "California"]

california_count = states.count("California")
print(f"California appears {california_count} times in the list.")

Output:

California appears 3 times in the list.

I executed the above example code and added the screenshot below.

Python Count Occurrences in Arrays and Lists

When to use list.count()

  • You only care about one specific value
  • The list is not extremely large
  • You want very simple, readable code

Limitations

  • It scans the list each time you call it; calling it repeatedly for many values can be slow on large datasets
  • It does not give you counts for all values at once

Method 2: Use collections.Counter for All Values

When you want counts for every unique value in your list, collections.Counter is usually the most convenient and often the most efficient option. It builds a frequency map (a dictionary-like object) where keys are values from your list and values are their counts.

from collections import Counter

# Example: Counting occurrences of all states
states = ["California", "Texas", "New York", "California", "Texas", "California"]

state_counts = Counter(states)
print(state_counts)

print(f"California appears {state_counts['California']} times in the list.")

Output:

Counter({'California': 3, 'Texas': 2, 'New York': 1})
California appears 3 times in the list.

I executed the above example code and added the screenshot below.

Count Occurrences in Arrays and Lists in Python

Why Counter is useful

  • You get counts for all distinct values in one pass
  • The API is convenient: you can treat it like a Python dictionary
  • It integrates well with other tools from the standard library

Typical use case

  • Aggregating categorical data (for example, survey responses, event names, labels in datasets)
  • Quickly summarizing the distribution of values.

Method 3: Use List Comprehensions and sum()

Sometimes you want to count occurrences while applying a condition or filter. In those cases, combining a generator expression or list comprehension with sum() gives you an expressive, readable pattern.

# Example: Counting occurrences using a condition
states = ["California", "Texas", "New York", "California", "Texas", "California"]

california_count = sum(1 for state in states if state == "California")
print(f"California appears {california_count} times in the list.")

Output:

California appears 3 times in the list.

I executed the above example code and added the screenshot below.

Count Occurrences in Arrays and Lists Python

When this pattern shines

  • You want to count values that satisfy a more complex condition
  • You might need to normalize or transform values before counting

For example, case-insensitive counting:

# Case-insensitive counting
states = ["california", "California", "CALIFORNIA", "Texas"]

california_count = sum(
1 for state in states
if state.lower() == "california"
)
print(f"California appears {california_count} times (case-insensitive).")

This pattern gives you full control over the matching logic.

Method 4: Count in array Module Arrays

If you use the standard library array module for compact numeric storage, you can still use the same patterns. The array object supports iteration and behaves a lot like a list for counting.

from array import array

# Example: Counting in an array of integers
numbers = array("i", [1, 2, 3, 1, 2, 1])

ones_count = numbers.count(1)
print(f"1 appears {ones_count} times in the array.")

Output:

1 appears 3 times in the array.

Just like with lists, you can also use Counter or sum() with an array:

from collections import Counter
from array import array

numbers = array("i", [1, 2, 3, 1, 2, 1])

counts = Counter(numbers)
print(counts)

Output:

Counter({1: 3, 2: 2, 3: 1})

Method 5: Count Occurrences in NumPy Arrays

In data science and machine learning projects, NumPy arrays are the standard way to represent numeric data. NumPy provides efficient tools to count occurrences.

Using numpy.count_nonzero

numpy.count_nonzero counts how many elements satisfy a condition:

import numpy as np

# Example: Counting occurrences in a NumPy array
arr = np.array([1, 2, 3, 1, 2, 1])

ones_count = np.count_nonzero(arr == 1)
print(f"1 appears {ones_count} times in the NumPy array.")

Output:

1 appears 3 times in the NumPy array.

I executed the above example code and added the screenshot below.

In Python Count Occurrences in Arrays and Lists

Using numpy.unique with return_counts

If you want all value counts at once, numpy.unique with return_counts=True is a standard pattern:

import numpy as np

arr = np.array([1, 2, 3, 1, 2, 1])

unique_values, counts = np.unique(arr, return_counts=True)

for value, count in zip(unique_values, counts):
print(f"{value}: {count} occurrences")

Output:

1: 3 occurrences
2: 2 occurrences
3: 1 occurrences

When to prefer NumPy

  • Arrays are large (for example, millions of elements)
  • You already use NumPy for other operations in your pipeline
  • You want vectorized operations and integration with machine learning libraries

Real-World Example: Analyze Survey Data

Let’s take a more realistic scenario: you have survey responses from different U.S. states, and you want to see how many responses came from each state.

from collections import Counter

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

state_counts = Counter(survey_data)

for state, count in state_counts.items():
print(f"{state}: {count} responses")

Possible output:

California: 5 responses
Texas: 5 responses
New York: 4 responses
Florida: 4 responses

This pattern is common in analytics and reporting tasks:

  • Aggregating responses by category (state, product, region)
  • Building summary tables for dashboards
  • Preprocessing categorical features for machine learning

Handle Large Datasets and Performance

For small lists, any of the methods above will perform well, and readability should guide your choice. For large datasets, performance becomes important.

Here is a simple benchmark-style example using a large list. The numbers you see will depend on your machine, but the pattern is what matters.

import time
from collections import Counter

# Generate a large list
large_survey_data = ["California"] * 1_000_000 + \
["Texas"] * 500_000 + \
["New York"] * 250_000

# 1. Using count()
start_time = time.time()
california_count = large_survey_data.count("California")
end_time = time.time()
print(f"count(): California appears {california_count} times. "
f"Time taken: {end_time - start_time:.4f} seconds")

# 2. Using Counter
start_time = time.time()
state_counts = Counter(large_survey_data)
end_time = time.time()
print(f"Counter: California appears {state_counts['California']} times. "
f"Time taken: {end_time - start_time:.4f} seconds")

Typical observations:

  • list.count() is efficient if you call it once for a single value
  • Counter can be more efficient if you need counts for many values, because it only scans the list once
  • For very large numeric arrays, NumPy-based approaches can be faster and more memory-efficient

Practical performance tips

  • Use list.count() for simple one-off checks
  • Use Counter when you want a frequency table for all values
  • Use NumPy (np.count_nonzeronp.unique) in numeric and ML workflows

Count with Conditions and Filters

Real datasets are often messy: missing values, different casing, extra whitespace, or special codes that you want to ignore. Combining sum() with generator expressions gives you flexible, readable control.

Example: Ignoring missing values

responses = ["Yes", "No", None, "YES", "yes", "No", ""]

yes_count = sum(
1 for response in responses
if response is not None
and response.strip() != ""
and response.strip().lower() == "yes"
)

print(f"Yes responses: {yes_count}")

Example: Count values above a threshold

scores = [45, 67, 89, 90, 67, 45, 92, 100, 53]

# Count scores greater than or equal to 90
high_scores = sum(1 for score in scores if score >= 90)
print(f"High scores: {high_scores}")

These patterns are particularly valuable when preparing features or applying business rules in data pipelines.

Common Issues and How to Avoid Them

When counting occurrences, a few subtle issues can lead to incorrect results:

  1. Case differences
    • "California" and "california" are different strings
    • Normalize using .lower() or .upper() before comparing
  2. Trailing or leading whitespace
    • "California " and "California" are not equal
    • Use .strip() before comparison
  3. None and missing values
    • Decide whether to ignore, treat separately, or replace them
    • Handle None explicitly in your conditions
  4. Floating-point comparisons
    • Comparing floats for equality can be tricky due to precision
    • For numeric data, sometimes you want to count values within a tolerance instead

Example with normalization:

raw_states = [" California", "california", "CALIFORNIA ", "Texas"]

normalized_states = [state.strip().lower() for state in raw_states]

from collections import Counter
state_counts = Counter(normalized_states)

print(state_counts)

Output:

Counter({'california': 3, 'texas': 1})

Summary Table: Which Method Should You Use?

Below is a quick reference to help you choose the right method based on your use case.

ScenarioRecommended Method
Count a single value in a small listlist.count()
Get counts for all values in a listcollections.Counter
Count with conditions or filterssum(1 for x in data if condition)
Count in array module arraysarray.count() or Counter(array)
Count in large numeric NumPy arraysnp.count_nonzeronp.unique
Prepare categorical counts for analytics/MLcollections.Counter or np.unique

Complete Example: From Raw Data to Clean Counts

To tie everything together, here is a slightly more realistic end-to-end example that simulates a small data-cleaning and counting pipeline.

from collections import Counter

raw_states = [
"California", " california ", "CALIFORNIA",
"Texas", "texas", "New York", None, "",
"Florida", " florida", "NEW YORK "
]

# Step 1: Clean and normalize data
clean_states = []
for state in raw_states:
if state is None:
continue # ignore missing values
normalized = state.strip()
if not normalized:
continue # ignore empty strings
clean_states.append(normalized.title()) # e.g., "california" -> "California"

# Step 2: Count occurrences
state_counts = Counter(clean_states)

# Step 3: Display results
for state, count in state_counts.items():
print(f"{state}: {count} occurrences")

Possible output:

California: 3 occurrences
Texas: 2 occurrences
New York: 2 occurrences
Florida: 2 occurrences

This example shows:

  • How to prepare and clean data before counting
  • How to normalize case and whitespace
  • How to use Counter to get clear, interpretable results

You may also like to 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.