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.
Install & Compatibility
Where this runs
tested against v4.1.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.925 runs
installs and imports cleanly · install 0.0s · import 0.012s · 17.8MB
glibcpy 3.10–3.925 runs
installs and imports cleanly · install 1.5s · import 0.007s · 18MB
16MB installed
● package 16MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
OrderedSet
✓ from ordered_set import OrderedSet
✗ from orderedset import OrderedSet
There are multiple packages with similar names. Ensure you are importing from 'ordered_set' (underscore) as installed by 'pip install ordered-set' (hyphen).
Demonstrates basic creation, membership testing, indexing, adding elements, and set operations with OrderedSet.
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'])
Debug
Known issues
gotchaPython'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.fixUse `OrderedSet` when you need both set semantics (uniqueness, set operations) and explicit order-based integer indexing/slicing.
affects: All versions on Python >= 3.7
gotchaThe `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.fixBenchmark your specific use case if deletion performance is critical. For most scenarios, the O(1) operations are sufficient.
affects: All versions
gotchaThe `.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`.fixBe aware of the return value of `.add()`. If you need to check if an item was newly added, you might compare the length before and after, or check `item not in my_set` before adding.
affects: All versions
gotchaThere 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.fixAlways use `pip install ordered-set` and `from ordered_set import OrderedSet`. Verify the documentation for the specific package you intend to use.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'ordered_set'
This error occurs when the 'ordered-set' library is not installed in the Python environment, or is installed but the import statement uses an incorrect module name.
fixEnsure the library is installed using pip and the import statement is correct. The package name on PyPI is 'ordered-set', but the module name for import is 'ordered_set'.
```python
pip install ordered-set
from ordered_set import OrderedSet
```
TypeError: unhashable type: 'OrderedSet'
Python's built-in `set`s and dictionary keys require their elements to be 'hashable' (immutable). An `OrderedSet` object is mutable, meaning its contents can change after creation, and therefore it is not hashable. This error occurs when trying to add an `OrderedSet` as an element to another `set` or `OrderedSet`, or use it as a key in a dictionary.
fixIf you need to store `OrderedSet` instances in another set or use them as dictionary keys, convert them to an immutable (hashable) representation first, such as a tuple of their elements, or use a `frozenset` if order is not critical for the inner elements.
```python
from ordered_set import OrderedSet
os1 = OrderedSet()
os2 = OrderedSet()
# Incorrect: Trying to put mutable OrderedSets into a set
# my_set_of_orderedsets = {os1, os2} # This would raise the TypeError
# Correct: Convert to tuple for hashability
my_set_of_tuples = {tuple(os1), tuple(os2)}
print(my_set_of_tuples)
# Correct: If order isn't critical for the inner set, use frozenset
# my_set_of_frozensets = {frozenset(os1), frozenset(os2)}
# print(my_set_of_frozensets)
``` TypeError: unhashable type: 'list'
Similar to the `OrderedSet` itself, mutable objects like Python `list`s cannot be elements of a `set` (or `OrderedSet`) because their contents can change, which would invalidate their hash value. This error occurs when you attempt to add a `list` directly into an `OrderedSet`.
fixConvert the mutable `list`s to immutable `tuple`s before adding them to the `OrderedSet`. Tuples are hashable and can be members of sets.
```python
from ordered_set import OrderedSet
my_list =
my_another_list =
my_ordered_set = OrderedSet()
# Incorrect: Adding a list directly
# my_ordered_set.add(my_list) # This would raise the TypeError
# Correct: Add a tuple instead
my_ordered_set.add(tuple(my_list))
my_ordered_set.add(tuple(my_another_list))
print(my_ordered_set)
```
AttributeError: module 'collections' has no attribute 'MutableSet'
This error typically occurs in Python versions 3.3 and later when code attempts to import `MutableSet` (or other Abstract Base Classes) directly from the `collections` module. These ABCs were moved to `collections.abc` in Python 3.3. While `ordered-set` (v4.1.0) correctly imports from `collections.abc` internally, this error can arise if a user's own code or another dependency tries to subclass or reference `collections.MutableSet` when interacting with or expecting an `OrderedSet`.
fixUpdate your code or the problematic dependency to import `MutableSet` from `collections.abc` instead of `collections`.
```python
# Incorrect import (for Python 3.3+):
# from collections import MutableSet
# Correct import:
from collections.abc import MutableSet
# Example usage (if defining a custom class that needs MutableSet):
class MyCustomSet(MutableSet):
# ... implementation ...
pass
``` Audit
Dependencies
No dependency data recorded yet.