- Aliases
- and operator
- Arrays
- Booleans
- Classes
- Code blocks
- Comments
- Conditional statements
- Console
- Data structures
- datetime module
- Decorator
- Dictionaries
- Docstrings
- enum
- enumerate() function
- Equality operator
- Exception handling
- False
- File handling
- Filter()
- Floats
- For loops
- Formatted strings
- Functions
- Generator
- Globals()
- Greater than operator
- Greater than or equal to operator
- If statement
- in operator
- Indices
- Inequality operator
- Integers
- Iterator
- Lambda function
- Less than operator
- Less than or equal to operator
- List append() method
- List comprehension
- List count()
- List insert() method
- List pop() method
- List sort() method
- Lists
- Logging
- map() function
- Match statement
- Math module
- Merge sort
- Min()
- Modules
- Multiprocessing
- Multithreading
- None
- not operator
- OOP
- or operator
- Parameters
- print() function
- Property()
- Random module
- range() function
- Recursion
- Reduce()
- Regular expressions
- requests Library
- return statement
- round() function
- Sets
- SQLite
- String decode()
- String find()
- String join() method
- String replace() method
- String split() method
- String strip()
- Strings
- Ternary operator
- time.sleep() function
- True
- try...except statement
- Tuples
- Variables
- While loops
- Zip function
PYTHON
Python list.count()
: Syntax, Usage, and Examples
When you want to know how many times a particular value appears in a list, Python makes it simple with the built-in list.count()
method. You don't have to write custom loops or use additional libraries—just call the method directly on the list. The count()
method is useful for tasks like data validation, frequency analysis, filtering, or tracking the popularity of items in user-generated content.
If you need to count a list Python-style without making things complicated, this method delivers both simplicity and power.
How to Use Python List Count
The syntax is:
list.count(value)
You provide the value you want to count. The method returns the number of times that value appears in the list.
Example
colors = ["red", "blue", "green", "red", "yellow"]
print(colors.count("red")) # Output: 2
In this case, "red"
appears twice.
When to Use List Count in Python
You should use count()
when:
- You want to measure how often an item occurs
- You're validating input or enforcing limits
- You need a quick frequency check in a dataset
- You're analyzing text, responses, or user data
It’s one of the simplest ways to answer “how many times does this show up?”
Practical Examples of Python List Count
Count Numbers in a List
numbers = [1, 2, 3, 4, 2, 2, 5]
count_of_twos = numbers.count(2)
print(count_of_twos) # Output: 3
This is especially helpful for filtering or highlighting duplicates.
Count Words in a List
words = ["apple", "banana", "apple", "cherry"]
print(words.count("apple")) # Output: 2
Great for word games, spell-checking, or analyzing text.
Check If an Item Is Present
items = ["pen", "pencil", "notebook"]
if items.count("pen") > 0:
print("Item is available.")
You can use count()
instead of in
when you want to go beyond checking existence and need the actual count.
Count Booleans or Flags
flags = [True, False, True, True]
on_count = flags.count(True)
print(on_count) # Output: 3
A clean way to summarize states or toggle values.
Count List Count Occurrences in Python Case-Insensitive
You can normalize items to lower case to count in a case-insensitive way:
names = ["Anna", "anna", "ANNA"]
count = [name.lower() for name in names].count("anna")
print(count) # Output: 3
Counting Items Using User Input
If you're building an app that asks users to enter data, you can track the number of repeats with count()
:
responses = ["yes", "no", "yes", "maybe", "yes"]
print("yes count:", responses.count("yes")) # Output: 3
You can use this pattern for surveys, votes, polls, or simple data logging.
Learn More About list.count() in Python
Count a List Python Style with Non-Primitives
You can count any item that supports equality comparison. That includes numbers, strings, booleans, and even tuples.
pairs = [(1, 2), (3, 4), (1, 2)]
print(pairs.count((1, 2))) # Output: 2
If you’re working with dictionaries or custom classes, count won’t work unless you've defined how equality behaves.
Count Items That Match a Condition
The count()
method looks for exact matches. To count items by condition, use a comprehension:
nums = [10, 20, 30, 40]
above_25 = len([n for n in nums if n > 25])
print(above_25) # Output: 2
This gives you flexibility when the built-in count alone isn’t enough.
Count Multiple Values
Python’s list.count()
counts one value at a time. If you need to get counts of multiple elements, use a dictionary or collections.Counter
.
from collections import Counter
fruits = ["apple", "banana", "apple", "cherry", "banana"]
counts = Counter(fruits)
print(counts["banana"]) # Output: 2
Counter
is a better tool for counting everything at once.
Compare count()
to len()
len(list)
gives you the total number of elements.list.count(x)
gives you the number of timesx
appears.
You can use both in tandem to analyze the dataset:
data = [1, 1, 2, 3, 1]
print(f"{data.count(1)} out of {len(data)} values are 1s")
Count Items in Nested Lists
count()
doesn’t search deeply into nested lists:
nested = [[1, 2], [1, 2], [3, 4]]
print(nested.count([1, 2])) # Output: 2
But if you try to count 1
, it returns 0
because [1, 2]
is not the same as 1
.
To count deeply, flatten the list first:
flat = [item for sub in nested for item in sub]
print(flat.count(1)) # Output: 2
Common Use Cases
Survey Analysis
answers = ["A", "B", "A", "C", "A", "B"]
print("A:", answers.count("A"))
print("B:", answers.count("B"))
print("C:", answers.count("C"))
This works well for tallying quiz answers or form responses.
Tag or Category Counts
tags = ["news", "sports", "news", "tech"]
print(tags.count("news")) # Output: 2
Handy for dashboards, filters, and data summaries.
Data Cleaning Checks
entries = ["yes", "no", "yes", ""]
blanks = entries.count("")
print("Missing entries:", blanks)
Quickly identify empty or default values.
What to Keep in Mind
count()
performs a linear search every time you call it. It’s fast enough for small lists, but for larger datasets, consider precomputing counts withCounter
.- It only matches exact values. You won’t get partial matches unless you process the list first.
- It’s case-sensitive for strings.
- The list doesn’t get modified.
count()
is read-only and returns a new integer.
The Python list count method is a lightweight but powerful way to tally specific items in any list. Whether you're validating input, analyzing results, filtering data, or tracking duplicates, the method gives you a quick answer to “how many of these are there?” You’ll use this function constantly in real-world Python programming, especially when working with user input, logs, tags, datasets, or reports.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.