Python ordered set: The Complete Guide

As for Python 3.7 and CPython 3.6, regular dict is confirmed to preserve order and perform better than OrderedDict.

To use a dictionary as an ordered set to filter out duplicate elements while maintaining order, emulate an ordered set.

Python ordered set

There are no built-in functionalities as an ordered set, but many packages can help you with OrderedSet. To use the Ordered Set in Python, use the ordered-set package.

There are other packages available as well.

  1. ordered-set (Python-based)
  2. orderedset (CPython based)
  3. collections-extended
  4. boltons (under iterutils.IndexedSet, Python-based)
  5. oset
  6. 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 them 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. Some benefits of using sortedcontainers include pure Python, fast-as-C implementations, 100% unit test coverage, and 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 are sorted in ascending order by default.

Now, let’s change the order of the lists while passing them 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 ascending order by default.

That is it for OrderedSet in Python.

Related posts

Python set contains

Python set add

Python set discard

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.