How to count the occurrences of an element in a list in Python?
Published on Aug. 22, 2023, 12:17 p.m.
To count the occurrences of an element in a list in Python, you can use the count()
method of the list object. Here’s an example:
my_list = [1, 2, 3, 1, 1, 4, 5, 2]
count_of_ones = my_list.count(1)
print(count_of_ones)
Output:
3
In this example, we define a list of numbers and then use the count()
method to count the number of times the number 1 appears in the list. The resulting count is 3.
Alternatively, you can use the Counter
class from the collections
module to get a dictionary with the count of each element in the list. Here’s an example:
from collections import Counter
my_list = [1, 2, 3, 1, 1, 4, 5, 2]
counts = Counter(my_list)
print(counts)
Output:
Counter({1: 3, 2: 2, 3: 1, 4: 1, 5: 1})
In this example, we use the Counter
class to get a dictionary with the count of each element in the list. The resulting dictionary shows that the number 1 appears 3 times, the number 2 appears twice, and so on.