Extra Python Collections - bags (multisets) and setlists (ordered sets)
collections_extended is a pure Python module with no dependencies providing various extended collection types. It includes a bag (multiset) class, a setlist (ordered set / unique list) class, a bijection, a RangeMap, and an IndexedDict. It also offers frozen (hashable) variants of bags and setlists. The current version, 2.0.2, maintains an active development status with regular updates and is compatible with Python 3.7+.
Warnings
- breaking Version 2.0.0 dropped support for Python 2.7, 3.4, and 3.5. Ensure your environment is Python 3.6 or later for v2.x.
- breaking When multiplying `bag` objects, the behavior changed in v2.0.0. It now produces a cartesian product as a tuple, rather than adding elements.
- breaking As of v2.0.0, `bags` no longer inherit from `Set`, meaning they cannot be compared for equality directly with `Set` objects.
- breaking Internal base classes `_basebag` and `_basesetlist` were renamed to `Bag` and `SetList` respectively and are now exposed in v2.0.0.
- gotcha Calling `setlist.insert(index, element)` will raise a `ValueError` if the `element` is already present in the `setlist`.
- gotcha `setlist` objects are not comparable using ordering operators (`<`, `>`, `<=`, `>=`) due to the ambiguity between set comparison and order-based comparison. Equality (`==`, `!=`) still works.
Install
-
pip install collections-extended
Imports
- bag
from collections_extended import bag
- setlist
from collections_extended import setlist
- IndexedDict
from collections_extended import IndexedDict
- RangeMap
from collections_extended import RangeMap
- bijection
from collections_extended import bijection
- frozenbag
from collections_extended import frozenbag
- frozensetlist
from collections_extended import frozensetlist
Quickstart
from collections_extended import bag, setlist, IndexedDict, RangeMap
from datetime import date
# Example with bag (multiset)
b = bag('abracadabra')
print(f"Bag: {b}, Count of 'a': {b.count('a')}")
b.remove('a')
print(f"Bag after removing 'a': {b}, Count of 'a': {b.count('a')}")
# Example with setlist (ordered set)
sl = setlist('abracadabra')
print(f"Setlist: {sl}, element at index 3: {sl[3]}")
try:
sl.insert(1, 'd')
except ValueError as e:
print(f"Attempted to insert duplicate into setlist: {e}")
# Example with IndexedDict
idict = IndexedDict({'a': 1, 'b': 2, 'c': 3})
print(f"IndexedDict: {idict}, value at index 1: {idict.iloc[1]}")
# Example with RangeMap
version_map = RangeMap()
version_map[date(2017, 10, 20): date(2017, 10, 27)] = '0.10.1'
version_map[date(2017, 10, 27):] = '1.0.0'
print(f"Version for 2017-10-24: {version_map[date(2017, 10, 24)]}")