Multiset

3.2.0 · active · verified Thu Apr 16

An implementation of a multiset, similar to Python's built-in `set` but allowing elements to occur multiple times. It supports standard set operations like union, intersection, and difference. The library is actively maintained, with version 3.2.0 released in 2024, and incorporates regular updates for new Python versions and minor feature enhancements.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to create mutable and immutable multisets, add elements, check multiplicities, and perform basic set operations.

from multiset import Multiset, FrozenMultiset

# Create a mutable multiset from an iterable
m1 = Multiset('banana')
print(f"Initial multiset: {m1}")
# Output: Initial multiset: {b, a, n, a, n, a}

# Add elements
m1.add('apple', multiplicity=2)
print(f"After adding apples: {m1}")
# Output: After adding apples: {b, a, n, a, n, a, apple, apple}

# Check multiplicity (count) of an element
print(f"Count of 'a': {m1.get('a')}")
# Output: Count of 'a': 3

# Perform set operations
m2 = Multiset(['a', 'p', 'p', 'l', 'e'])
intersection = m1 & m2
print(f"Intersection of m1 and m2: {intersection}")
# Output: Intersection of m1 and m2: {a, a, apple, p, l, e}

# Create an immutable, hashable multiset
f1 = FrozenMultiset([1, 1, 2, 3])
f2 = FrozenMultiset([1, 2, 2, 4])
print(f"Frozen multiset f1: {f1}")
# Output: Frozen multiset f1: {1, 1, 2, 3}

# Frozen multisets can be used in sets or as dict keys
my_set_of_multisets = {f1, f2}
print(f"Set of frozen multisets: {my_set_of_multisets}")
# Output: Set of frozen multisets: {{1, 1, 2, 3}, {1, 2, 2, 4}}

view raw JSON →