How to Subtract Counters in Python for Bag Differences

Use the Counter class's subtraction operator to compute bag differences, removing items and counts that appear in one multiset but not the other.

Easy Python 3.10+ Aug 9, 2026 Dictionaries & sets 14 views 0 copies

Python code

11 lines
Python 3.10+
from collections import Counter

def subtract_counters(bag1, bag2):
    """Return the difference of two Counters (bag1 - bag2)."""
    return bag1 - bag2

if __name__ == "__main__":
    inventory = Counter(apples=10, bananas=5, oranges=3)
    sold = Counter(apples=4, bananas=2, grapes=2)
    remaining = subtract_counters(inventory, sold)
    print("Remaining:", dict(remaining))

Output

stdout
Remaining: {'apples': 6, 'bananas': 3}

How it works

The Counter class supports the subtraction operator (-) which subtracts counts for matching keys and removes keys whose result is zero or negative. This is a multiset (bag) operation — it only keeps positive counts, so items with equal or higher counts in the subtrahend are dropped entirely. The operator returns a new Counter object, leaving the original inputs unchanged. This makes it ideal for inventory or stock-level calculations where you want to see what's left after a transaction.

Common mistakes

  • Using `subtract()` (which can leave zero/negative counts) instead of the `-` operator
  • Forgetting that keys not in bag1 but in bag2 are ignored and never appear in the result
  • Assuming subtraction is symmetric — `bag2 - bag1` gives a completely different result

Variations

  1. Use `bag1.subtract(bag2)` if you need in-place modification and want to inspect intermediate negative values
  2. Convert the result to a regular dict with `dict(remaining)` for display or JSON serialization

Real-world use cases

  • Tracking warehouse stock levels after a shipment goes out — subtract sold units from the current inventory.
  • Comparing two versions of a feature flag configuration to see which settings were removed or reduced.
  • Computing the difference between sent and received message counters in a telemetry pipeline to spot delivery losses.

Sponsored

Run this sample

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

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.