An ordered set stores unique elements while preserving the order in which they are added. It combines the uniqueness property of a set with the ordered behavior of a list. For Example:
Input: {1, 2, 3, 4}
Output (Unordered Set): {3, 1, 4, 2} # Order may vary
Output (Ordered Set): {1, 2, 3, 4}
Explanation: An unordered set may display elements in any order, while an ordered set always maintains the insertion order.
Ordered Set Module
By default, Python provides an unordered set, which does not preserve insertion order. To create an ordered set, you can use the external ordered-set module, which maintains both uniqueness and insertion order.
Install the module using the pip package manager:
pip install ordered_set
Below is the syntax:
OrderedSet(iterable)
Here, the iterable (such as a list) provides the elements for the ordered set. Duplicate values are automatically removed while preserving the order.
from ordered_set import OrderedSet
res = OrderedSet(['a', 'b', 'c', 'b', 'd'])
print(res)
for item in res:
print(item, end=" ")
Output
OrderedSet(['a', 'b', 'c', 'd'])
a b c d
Using Dictionary Data Structure
A dictionary can be used to create an ordered set because dictionary keys are unique and preserve insertion order (Python 3.7+). By storing elements as keys and assigning None as values, duplicates are automatically removed while the order is maintained.
data = { "a": None, "b": None, "c": None, "a": None, "d": None}
print(data)
for key in data.keys():
print(key, end=" ")
Output
{'a': None, 'b': None, 'c': None, 'd': None}
a b c d Explanation: Duplicate keys ("a") are ignored and the dictionary keeps elements in the order they were first added.
Using List Data Structure
A list stores elements in order but allows duplicates. To use a list as an ordered set, duplicates must be manually removed while keeping the original order intact.
x = ["a", "b", "c", "a", "b", "d"]
ordered_items = []
for item in x:
if item not in ordered_items:
ordered_items.append(item)
print(ordered_items)
Output
['a', 'b', 'c', 'd']
Explanation: Each element is added to a new list only if it is not already present in that list. This removes duplicates while preserving the insertion order.