Python List count() Function
The List count()
method returns the number of times the specified element appears in the list.
Syntax
my_list.count(element)
count() Parameters
Python List count()
method parameters::
Parameter | Condition | Description |
---|---|---|
item | Required | Any item (of type string, list, set, etc.) you want to search for. |
count() Return Value
Python List count()
function returns
Examples
Example 1: Return the number of occurrences of an Item in a List
For example, let's count number of occurrences of green
:
my_list = ['red', 'green', 'blue']
print(my_list.count('green')) # Output: 1
output
1
For example, let's count number of occurrences of number 9
:
my_list = [1, 9, 1, 9, 2, 7, 3, 9, 0]
print(my_list.count(9)) # Output: 3
output
3
Example 2: Count Multiple Items
If you want to count multiple items in a list, you can call count()
in a loop.
items = ['a', 'b', 'c', 'b', 'b', 'a', 'a', 'c']
counts = {}
for item in set(items):
counts[item] = items.count(item)
print(counts) # Output: {'b': 3, 'a': 3, 'c': 2}
output
{'b': 3, 'a': 3, 'c': 2}
However, this approach requires a separate pass over the list for every count()
call: catastrophic for performance!.
Instead, it is better to use couter()
method from class collections.
For example, count occurrences of all the unique items:
my_list = ['a', 'b', 'c', 'b', 'b', 'a', 'a', 'c']
from collections import Counter
print(Counter(my_list)) # Output: Counter({'a': 3, 'b': 3, 'c': 2})
output
Counter({'a': 3, 'b': 3, 'c': 2})
Example 3: Check if there are duplicates with count()
You can use count()
method to check if a certain element appears more than once in the list, i.e. count()
returns a number bigger than 1.
my_list = ['apple', 'banana', 'apple', 'orange', 'banana']
for item in my_list:
if my_list.count(item) > 1:
print(f"{item} is duplicated.")
output
apple is duplicated.
banana is duplicated.
apple is duplicated.
banana is duplicated.
Example 4: Count the number of occurrences of a character or a word in a String
You can use count()
method to get the number of occurrences of a character or a word in a string.
By converting the string to a list or iterating through the string, you can count the occurrences of any character or substring
text = "Hello world!"
char_to_count = 'l'
print(f"Occurrences of '{char_to_count}':", text.count(char_to_count))
output
Occurrences of 'l': 3