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 to OrderedSet. 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 OrderedSet
iterable = "hello-educative"
ordr_set = OrderedSet(iterable)
print(ordr_set)

Explanation

  • Line 1: We import OrderedSet from the sortedcollections module.
  • Line 3: We define a string iterable called iterable.
  • Line 5: We create an ordered set called ordr_set by passing the iterable as an argument to the OrderedSet constructor.
  • 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.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved