5 tricks to maintain the order in a set in Python

Updated: February 12, 2024 By: Guest Contributor Post a comment

Introduction

While a standard set in Python is known for not maintaining any order, there are instances where the sequence in which items are added is valuable. This tutorial walks through various methods and tricks to preserve the order of elements in a ‘set-like’ collection in Python. We delve into the basics before escalating to more advanced techniques, accompanied by code examples and outputs where applicable.

Understanding the Standard Set

Before diving into solutions, it’s essential to comprehend the nature of a Python set. A set is a collection type that is unordered, mutable, and prohibits duplicate elements. Its unordered nature means that the items do not maintain the order in which they were added. Here’s a quick example:

my_set = {3, 1, 4, 1, 5, 9, 2}
print(my_set)

Output might vary since the set is unordered. A probable output is:

{1, 2, 3, 4, 5, 9}

Using Lists for Order

The simplest workaround to mimic an ordered set is to use a list, ensuring the uniqueness of elements manually before adding them. This is a straightforward approach that comes handy for smaller sets.

ordered_list = []
nums = [1, 2, 3, 1, 4, 5, 6, 2]
for num in nums:
if num not in ordered_list:
ordered_list.append(num)
print(ordered_list)

Output:

[1, 2, 3, 4, 5, 6]

collections.OrderedDict

For a more set-like behavior while maintaining order, Python’s collections.OrderedDict can be leveraged. Introduced to maintain order of keys, it can be cleverly used as an ordered set by simply ignoring the values and just focusing on the keys.

from collections import OrderedDict

ordered_set = OrderedDict.fromkeys([1, 2, 3, 2, 4, 1])
print(list(ordered_set))

Output:

[1, 2, 3, 4]

Using the keys of a dict

From Python 3.7 onwards, the standard dict type maintains insertion order. This means we can utilize a dict, using just its keys as an ordered set.

ordered_set = {}.fromkeys([1, 2, 3, 1, 4, 4, 5]).keys()
print(list(ordered_set))

Output:

[1, 2, 3, 4, 5]

Third-Party Packages

Several third-party packages also offer solutions for maintaining order in a set. One such example is ordered-set package. It provides an OrderedSet class which is basically a hybrid between a list and a set, maintaining the order of elements while ensuring uniqueness.

from ordered_set import OrderedSet

o_set = OrderedSet([1, 2, 3, 2, 1])
print(list(o_set))

Output:

[1, 2, 3]

Converting to a set and back to a list

While this method loses the essence of keeping order while adding elements, it’s worth mentioning as a ‘hack’ if the order is to be established after all elements are added. This method involves adding elements to a set for uniqueness, then converting the set back to a list.

nums = [1, 2, 3, 1, 4, 5, 6, 2]
unique_nums = list(set(nums))
print(unique_nums)

Note: This method does not maintain insertion order; it’s merely a technique to remove duplicates after all elements are in the collection.

Conclusion

Maintaining order in a set in Python involves leveraging other collection types or third-party libraries to achieve ‘set-like’ behavior while preserving the sequence of elements. Whether you opt for lists, OrderedDict, dictionary keys, or external packages, each method serves a particular use case, providing flexibility in how we handle collections while maintaining uniqueness.