from collections import Counter # Counting elements in a list data_list = ["apple", "banana", "apple", "orange", "banana", "apple", "grape", "orange"] fruit_counts = Counter(data_list) print(f"Fruit counts: {fruit_counts}") # Counting characters in a string text = "hello world" char_counts = Counter(text) print(f"Character counts: {char_counts}") # Accessing counts print(f"Count of 'apple': {fruit_counts['apple']}") print(f"Count of 'mango' (not present): {fruit_counts['mango']}") # Returns 0 for missing items # Finding the most common elements print(f"Top 2 most common fruits: {fruit_counts.most_common(2)}") print(f"All items sorted by count: {fruit_counts.most_common()}") # Performing arithmetic operations on Counters (like merging counts) another_batch = Counter(["apple", "grape", "kiwi"]) total_counts = fruit_counts + another_batch print(f"Total counts after adding another batch: {total_counts}") # Subtracting counts fruit_counts.subtract({"apple": 1, "banana": 1}) print(f"Fruit counts after subtracting some: {fruit_counts}") # Elements method to iterate over elements repeatedly print("Elements in original order (not guaranteed, just example):") for item in sorted(fruit_counts.elements()): print(item, end=" ") print(" ") # Converting to a dictionary print(f"As dictionary: {dict(fruit_counts)}")