In this tutorial, we will learn how to count the occurrences of all items in a list in python, with some cool and easy examples, In many situations, you might have to come up with this type of requirements.
Using collections.counter:
To count the occurrences of all items in a list in python you can use the “collections.counter” class from the built-in collections module. Here’s an example:
from collections import Counter my_list = ['apple', 'banana', 'cherry', 'banana', 'apple', 'orange', 'apple'] # Create a Counter object item_counts = Counter(my_list) # Print the counts print(item_counts)
output:
Counter({'apple': 3, 'banana': 2, 'cherry': 1, 'orange': 1})
Using a loop:
You can also achieve the same result using a loop to iterate through the list and keep track of counts in a dictionary.However, this method is less efficient than using counter.
def count_occurrences(my_list):
"""
This function counts the occurrences of all items in a list using a loop.
Args:
my_list: A list of any data type.
Returns:
A dictionary where the keys are the elements from the list and the values are their counts.
"""
occurrences = {}
for item in my_list:
if item in occurrences:
occurrences[item] += 1
else:
occurrences[item] = 1
return occurrences
# Example usage
my_list = [1, 2, 2, 3, 1, 4, 2]
occurrences = count_occurrences(my_list)
print(occurrences)
output:
{2: 3, 1: 2, 3: 1, 4: 1}