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.

Copyright ©2024 Educative, Inc. All rights reserved