Python count list method is used to get the number of times an element appears in the list. This method returns the number of elements with the specified value.
list.count(element)
If the element is not present in the list, it returns 0.
Python count list
Simple example code.
numbers = [2, 3, 5, 2, 11, 2, 7]
# check the count of 2
count = numbers.count(2)
print('Count of 2:', count)
print('Count of 0:', numbers.count(0))
Output:
Using collections.Counter
:
from collections import Counter
my_list = [1, 2, 2, 3, 4, 2, 5, 6, 4]
# Count occurrences of all elements using Counter
element_counts = Counter(my_list)
# Access counts for specific elements
count_of_2 = element_counts[2]
print(f"Count of 2: {count_of_2}")
# Access counts for all unique elements
for element, count in element_counts.items():
print(f"Count of {element}: {count}")
The Counter
class provides a more efficient way to count occurrences of elements in a list or any iterable.
Do comment if you have any doubts or suggestions on this Python list method topic,
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.