How do I count occurrence of unique values inside a list?
To quickly count occurrences in a list, we utilize the Counter
from the collections
module:
Are you interested in unique value counts? Combine set()
with Counter
:
Counting with numpy
numpy
has got your back if you're dealing with numerical data. Use the unique
function:
User inputs and Counter
To count user-entered words until a blank line is entered:
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
:
Tabular data? Say hello to pandas
pandas.Series.value_counts
counts occurrences in data that resembles a table:
Custom counting with dictionary comprehension
When control is what you desire, a dictionary comprehension is what you require:
Was this article helpful?