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.
Python code
11 linesfrom 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
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
- Use `bag1.subtract(bag2)` if you need in-place modification and want to inspect intermediate negative values
- 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
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.