![]() |
VOOZH | about |
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.
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.
Output
OrderedSet(['a', 'b', 'c', 'd'])
a b c d
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.
{'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.
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.
['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.