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.

Easy Python 3.9+ Aug 9, 2026 OOP & classes 13 views 0 copies

Python code

31 lines
Python 3.9+
class 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

stdout
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

  1. Use `collections.Counter` for counting items instead of a custom class.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from OOP & classes

Related tutorials and quizzes for this topic.