Get count of a specific element in a list using Python
We can use the count() function of the Python list to get the count of a specific element in the list.
# Define a list
numbers = [4, 4, 5, 9, 4, 3, 6, 9]
# Get the frequency of 4
result = numbers.count(4)
# Print the result
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.
In the code snippet
- We have created a list called numbers that contains multiple items.
- We are using the count() function of the list and getting the frequency of 4 in the numbers list and assigning them to the result named variable.
- Printing the result.
As we have already explained the functionality of List.count() function in Python. The count() function returns the count of a specific item in the list.
my_list = ['a', 'b', 'a', 'c', 'd', 'a', 'a']
result = my_list.count('a')