Multiset with Counter update and elements in Python

Demonstrates using collections.Counter as a multiset: updating counts with update() and iterating elements() to get repeated items.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 13 views 0 copies

Python code

9 lines
Python 3.9+
from collections import Counter

multiset = Counter(['apple', 'banana', 'apple'])

multiset.update(['banana', 'cherry', 'apple'])

print("Elements after update:", sorted(multiset.elements()))
print("Counts:", dict(multiset))
print("Most common:", multiset.most_common(2))

Output

stdout
Elements after update: ['apple', 'apple', 'apple', 'banana', 'banana', 'cherry']
Counts: {'apple': 3, 'banana': 2, 'cherry': 1}
Most common: [('apple', 3), ('banana', 2)]

How it works

Counter is a dict subclass that maps items to their counts. The update() method adds counts from an iterable or another Counter, merging counts instead of replacing. elements() returns an iterator that repeats each item as many times as its count, in insertion order. The most_common(n) method returns a list of the n most common (item, count) pairs. This makes Counter ideal for multiset operations where you need to handle duplicates and frequencies.

Common mistakes

  • Using `multiset['apple'] = 1` instead of `update()` when you want to increment, which overwrites the count.
  • Forgetting that `elements()` returns an iterator, not a list — wrap it with `list()` or `sorted()`.
  • Assuming `elements()` includes items with zero or negative counts (it only yields positive counts).
  • Using `set()` on the Counter keys when you need to preserve duplicates.

Variations

  1. Use `multiset += Counter(['apple'])` to combine counts in place.
  2. Use `multiset.subtract(['apple'])` to decrement counts for a multiset difference.

Real-world use cases

  • Counting inventory items in a warehouse and updating stock as shipments arrive, then listing the items to pack.
  • Building a word frequency table from a text corpus and retrieving the most common terms for a tag cloud.
  • Tracking votes or survey responses where each response is a repeatable category and you need to update totals in real time.

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.