Home › Interview Questions › How would you count the occurrences of each fruit …

How would you count the occurrences of each fruit in a list using a for loop or collections.Counter in Python?

🟢 Easy Coding Junior level
2Times asked
Oct 2026Last seen
Oct 2026First seen

💡 Model Answer

You can count items in a list by iterating over the list and updating a dictionary that maps each item to its count. For example: fruits = ['apple', 'banana', 'apple', 'banana', 'apple']; result = {}; for fruit in fruits: result[fruit] = result.get(fruit, 0) + 1; print(result) # {'apple': 3, 'banana': 2}. The get method returns the current count or 0 if the key is missing. Alternatively, Python’s collections module provides Counter, which automates this: from collections import Counter; counts = Counter(fruits); print(counts) # Counter({'apple': 3, 'banana': 2}). Both approaches run in O(n) time, where n is the number of elements in the list.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.

Get Assisting AI — Starts at ₹500