Explain Codes LogoExplain Codes Logo

How do I count occurrence of unique values inside a list?

python
counting
unique-values
list-processing
Alex KataevbyAlex Kataev·Oct 5, 2024
TLDR

To quickly count occurrences in a list, we utilize the Counter from the collections module:

from collections import Counter counts = Counter(['apple', 'banana', 'apple', 'orange', 'banana', 'apple']) print(counts) # Counter({'apple': 3, 'banana': 2, 'orange': 1})

Are you interested in unique value counts? Combine set() with Counter:

unique_counts = Counter(set(['apple', 'banana', 'apple', 'orange', 'banana', 'apple'])) print(unique_counts) # Counter({'apple': 1, 'banana': 1, 'orange': 1})

Counting with numpy

numpy has got your back if you're dealing with numerical data. Use the unique function:

import numpy as np data = np.array(['apple', 'banana', 'apple', 'orange', 'banana', 'apple']) values, counts = np.unique(data, return_counts=True) print(dict(zip(values, counts))) #{'apple': 3, 'banana': 2, 'orange': 1} # Wanna slice of Apple 3 times or would you rather have Orange once?

User inputs and Counter

To count user-entered words until a blank line is entered:

user_input = input("Enter a word (blank line to finish): ") # Make your words count! words = [] while user_input: words.append(user_input) user_input = input("Enter a word (blank line to finish): ") print(Counter(words)) # And the word of the user is counted...

Remember, raw_input for Python 2 and input for Python 3. Long live Python 3!

Efficiency and advanced techniques

Memory management for large data

A large list? No problem. Counter is your friend, but hang on, len(set(list)) is your best friend here for memory-efficient unique counts.

Leveling up with list comprehensions

List comprehensions are a Pythonista's sword. Slice and dice with Counter:

comprehended_counts = Counter([x.lower() for x in ['APPLE', 'apple', 'Orange', 'ORANGE', 'BANANA']]) print(comprehended_counts) # Remember, an APPLE a day keeps CASE sensITIvity away!

Tabular data? Say hello to pandas

pandas.Series.value_counts counts occurrences in data that resembles a table:

import pandas as pd fruits_series = pd.Series(['apple', 'banana', 'apple', 'orange', 'banana', 'apple']) print(fruits_series.value_counts()) # Bear eats Panda, but Panda eats...?

Custom counting with dictionary comprehension

When control is what you desire, a dictionary comprehension is what you require:

fruit_list = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'] fruit_count = {x: fruit_list.count(x) for x in set(fruit_list)} print(fruit_count) # Count on me like 1, 2, 3...