What is OrderedSet() in Python?
OrderedSet() in Python
In Python, a set is a built-in data structure that only stores unique items.
Similar to OrderedDict, the OrderedSet maintains the insertion order of the elements.
Installation
The OrderedSet() function is provided by the sortedcollections module. This can be installed using pip:
pip install sortedcollections
Syntax
OrderedSet(iterable)
Parameter
iterable: This is the iterable to be converted toOrderedSet. The iterable can be a set, list, and so on.
Return value
This method returns an instance of OrderedSet.
Code
Let’s look at an example:
from sortedcollections import OrderedSetiterable = "hello-educative"ordr_set = OrderedSet(iterable)print(ordr_set)
Explanation
- Line 1: We import
OrderedSetfrom thesortedcollectionsmodule. - Line 3: We define a string iterable called
iterable. - Line 5: We create an ordered set called
ordr_setby passing theiterableas an argument to theOrderedSetconstructor. - Line 7: We print
ordr_set.
From the output, we can observe that no duplicate entries are present in the set, and the insertion order is preserved.
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved