How to Count Items in a Python Class
A beginner-friendly Inventory class that stores item quantities in a dictionary and provides add, remove, count, and summary methods.
Python code
31 linesclass Inventory:
def __init__(self):
self.items = {}
def add(self, item, quantity=1):
self.items[item] = self.items.get(item, 0) + quantity
def remove(self, item, quantity=1):
if item not in self.items:
raise ValueError(f"{item} not in inventory")
self.items[item] -= quantity
if self.items[item] <= 0:
del self.items[item]
def count(self):
return sum(self.items.values())
def summary(self):
return dict(sorted(self.items.items()))
if __name__ == "__main__":
cart = Inventory()
cart.add("apple", 3)
cart.add("banana")
cart.add("apple", 2)
print("Count:", cart.count())
print("Summary:", cart.summary())
cart.remove("apple", 4)
print("After removal:", cart.summary())
print("Count:", cart.count())
Output
Count: 6
Summary: {'apple': 5, 'banana': 1}
After removal: {'banana': 1}
Count: 1
How it works
The Inventory class wraps a dictionary to track quantities. The add method uses dict.get to safely increment existing or new items. The remove method raises a ValueError for missing items and deletes the key when quantity drops to zero, keeping the internal state consistent. The count method sums all values, and summary returns a sorted copy for stable display.
Common mistakes
- Forgetting to delete the item when quantity reaches zero, leaving it with a non-positive count.
- Using `self.items[item] = self.items[item] + quantity` without checking existence, causing a KeyError.
- Not returning a copy from `summary`, so callers can mutate the internal state.
Variations
- Use `collections.Counter` for counting items instead of a custom class.
- Add a `__contains__` method to check item presence with the `in` operator.
Real-world use cases
- Tracking stock quantities in a simple e-commerce warehouse system.
- Counting occurrences of words in a text when building a custom lexical analysis module.
- Managing quantities of ingredients in a recipe manager application.
Sponsored
More from OOP & classes
- Add property getter setter validation in Python easy
- Binary Tree Inorder Traversal in Python easy
- Borg pattern shared state in Python medium
- Bridge Pattern in Python: Separate Abstraction from Implementation medium
- Composable Predicates with the &, |, ~ Operators in Python medium
- Composition over Inheritance: How to Build a Wallet Account in Python easy
Keep learning
Related tutorials and quizzes for this topic.