What is Python Ordered Set and How to Preserve Order of Set
As of Python 3.7 and CPython 3.6, regular dict is confirmed to preserve order and is more performant than OrderedDict. To use a dictionary as an ordered set to filter out duplicate elements while preserving order, emulating an ordered set.
Python Ordered Set
There are no built-in functionalities as OrderedSet, but there are many packages that can help you with OrderedSet. These packages are the following.
- ordered-set (Python-based)
- orderedset (CPython based)
- collections-extended
- boltons (under iterutils.IndexedSet, Python-based)
- oset
- sortedcontainers
OrderedSet using boltons in Python
To work with boltons IndexSet, you need to install the boltons package.
python3 -m pip install boltons
Now, import the module using the following code.
from boltons.setutils import IndexedSet
Let’s use the IndexedSet and pass the two lists as arguments.
from boltons.setutils import IndexedSet data = IndexedSet(list(range(2)) + list(range(3, 6))) print(data)
Output
IndexedSet([0, 1, 3, 4, 5])
Now, let’s change the order of the lists while passing it to the IndexedSet.
from boltons.setutils import IndexedSet data = IndexedSet(list(range(3, 6)) + list(range(2))) print(data)
Output
IndexedSet([3, 4, 5, 0, 1])
You can see that the order of the set is preserved perfectly. It retains the order as they were added to the Python set.
OrderedSet in Python using sortedcontainers
Python sortedcontainers module provides a SortedSet for preserving the order of the set elements. There are some benefits of using sortedcontainers, including pure-Python, fast-as-C implementations, 100% unit test coverage, hours of stress testing.
Let’s install the sortedcontainers module using the pip package manager.
python3 -m pip install sortedcontainers
Now, import the module using the following code.
from sortedcontainers import SortedSet
Let’s use the SortedSet() method and pass the two lists as arguments.
from sortedcontainers import SortedSet data = SortedSet(list(range(2)) + list(range(3, 6))) print(data)
Output
SortedSet([0, 1, 3, 4, 5])
You can see that the returns set sorted in ascending order by default.
Now, let’s change the order of the lists while passing it to the SortedSet.
from sortedcontainers import SortedSet data = SortedSet(list(range(3, 6)) + list(range(2))) print(data)
Output
SortedSet([0, 1, 3, 4, 5])
You can see that even if we add elements to the set in a different order, it will return in the ascending order by default.
That is it for OrderedSet in Python.