list.count()
list.count(x) int · Updated March 14, 2026 · List Methods The .count() method returns the number of times a specified value appears in a list. It scans the list linearly and counts all occurrences of the given element, returning an integer. This is useful for frequency analysis, validation, and basic data exploration.
Syntax
list.count(x)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| x | any | — | The value to search for. Can be of any type: int, str, float, list, dict, object, etc. Comparisons use ==. |
Return Value
Returns an int representing how many times x appears in the list. Always returns 0 or a positive integer — never negative or a float.
Examples
Basic usage - counting numbers
Count how many times a number appears in a list:
numbers = [1, 2, 3, 2, 4, 2, 5, 2]
twos = numbers.count(2)
print(twos)
# 4
Counting strings
Count string occurrences in a list of words:
fruits = ["apple", "banana", "apple", "cherry", "apple"]
apples = fruits.count("apple")
print(apples)
# 3
Counting in a list with mixed types
Python lists can contain mixed types:
mixed = [1, "hello", 3.14, 1, 1, "hello"]
print(mixed.count(1))
# 3
print(mixed.count("hello"))
# 2
print(mixed.count(3.14))
# 1
Counting in an empty list
Calling .count() on an empty list always returns 0:
empty = []
print(empty.count("anything"))
# 0
Counting nested lists
When counting lists, Python compares by value, not reference:
nested = [[1, 2], [3, 4], [1, 2], [5, 6]]
print(nested.count([1, 2]))
# 2
Common Patterns
Frequency analysis
A common pattern is building a frequency dictionary:
data = ["apple", "banana", "apple", "cherry", "banana", "apple"]
unique = set(data)
frequencies = {item: data.count(item) for item in unique}
print(frequencies)
# {"apple": 3, "banana": 2, "cherry": 1}
Note: For large lists, collections.Counter is more efficient than repeated .count() calls.
Validation - checking for duplicates
Check if a list has any duplicate values:
items = [1, 2, 3, 4, 5, 3]
has_duplicate = any(items.count(item) > 1 for item in items)
print(has_duplicate)
# True
Conditional counting with comprehension
Count elements meeting a condition:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = sum(1 for n in numbers if n % 2 == 0)
print(evens)
# 5
Performance Note
- .count() performs a linear scan — O(n) time complexity
- It traverses the entire list regardless of how many matches found
- For repeated counts on the same list, consider building a collections.Counter once:
from collections import Counter
data = ["a", "b", "a", "c", "a", "b"]
counter = Counter(data)
print(counter["a"]) # 3 — O(1) lookup after O(n) build
print(counter["b"]) # 2
See Also
- list::list.append() — add elements to a list
- list::list.pop() — remove and return an element
- built-in::len — get the total length of a list
- collections::Counter — efficient counting for large datasets