OrderedSet
An OrderedSet is a custom MutableSet that remembers its order, so that every entry has an index that can be looked up. It combines the uniqueness of a set with the order-preserving and indexable properties of a list. The library is currently at version 4.1.0 and is actively maintained, with updates driven by new features and bug fixes.
Warnings
- gotcha Python's built-in `dict` (since 3.7) maintains insertion order for its keys. However, `OrderedSet` provides the full `MutableSet` API along with list-like integer indexing and slicing, which `dict` keys alone do not. Do not assume `dict.fromkeys()` provides equivalent functionality for all use cases.
- gotcha The `OrderedSet` implementation prioritizes O(1) performance for most operations (insertion, iteration, membership testing, index lookup) but deletion is O(N). If your primary use case involves frequent deletions from large sets, consider alternative data structures or performance implications.
- gotcha The `.add()` method of `OrderedSet` returns the integer index of the added item (or its existing index if already present), unlike the standard `set.add()` method which always returns `None`.
- gotcha There are multiple Python packages with similar names (e.g., `orderedset` (lowercase), `ordered-set-37`, `orderly-set`, or `sortedcollections.OrderedSet`). Ensure you install `ordered-set` (hyphenated) and import `OrderedSet` from `ordered_set` (underscore) to use this specific library. Different packages may have different APIs, features, and maintenance statuses.
Install
-
pip install ordered-set
Imports
- OrderedSet
from ordered_set import OrderedSet
Quickstart
from ordered_set import OrderedSet
# Create an OrderedSet
letters = OrderedSet('abracadabra')
print(f"Initial OrderedSet: {letters}")
# Expected: OrderedSet(['a', 'b', 'r', 'c', 'd'])
# Check for membership
print(f"'r' in letters: {'r' in letters}")
# Expected: 'r' in letters: True
# Get item by index
print(f"letters[2]: {letters[2]}")
# Expected: letters[2]: r
# Get index of an item
print(f"letters.index('r'): {letters.index('r')}")
# Expected: letters.index('r'): 2
# Add a new item (returns index)
new_index = letters.add('x')
print(f"After adding 'x': {letters}, index returned: {new_index}")
# Expected: After adding 'x': OrderedSet(['a', 'b', 'r', 'c', 'd', 'x']), index returned: 5
# Set operations
more_letters = OrderedSet('shazam')
letters |= more_letters
print(f"Union with 'shazam': {letters}")
# Expected: Union with 'shazam': OrderedSet(['a', 'b', 'r', 'c', 'd', 'x', 's', 'h', 'z', 'm'])