Sling Academy
Home/Python/5 tricks to maintain the order in a set in Python

5 tricks to maintain the order in a set in Python

Last updated: February 12, 2024

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.

Next Article: Python: How to add new elements to an existing set (4 ways)

Previous Article: Python: How to convert a set to a list and vice-versa

Series: Working with Dict, Set, and Tuple in Python

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types