How to Count Occurrences in a List with Python
In Python, to count the number of times an item appears in a list, you can use the count
method.
list_name.count(target_element)
The count
method searches for the specified element within the main list.
However, it does not search within any sublists that might be present inside the main list.
A Practical Example
Here is a list composed of several elements:
list = ['red', 'blue', 'green', 'red']
As you can see, the value "red" appears in two different elements of the list.
To count the number of elements that contain the value 'red', you would write the following command:
print(list.count('red'))
The output of this command is:
2
This simply tells us that there are two elements with the value 'red'.