An ordered set is a collection that combines the properties of both a set and a list. Like a set, it only keeps unique elements, meaning no duplicates are allowed. Like a list, it keeps the elements in the order they were added.
In Python, the built-in set does not maintain the order of elements, while a list allows duplicates. An ordered set solves this problem by keeping the uniqueness of a set while preserving the order of insertion.
Example:
input_dataSet = {"Prince", "Aditya", "Praveer", "Shiv"}
Output in case of unordered set: {"Aditya, "Prince", "Shiv", "Praveer"}, It can be random position on your side
Output in case of ordered set: {"Prince", "Aditya", "Praveer", "Shiv"}
Explanation: As you know in Python if you print this set more one time than, every time you will getting the random position of the items for the same dataset. But in case of ordered set you will getting the same dataset every time in same order you had inserted items.
Using the Ordered Set Module (or class)
In default, you have an unordered set in Python but for creating the ordered set you will have to install the module named ordered-set by pip package installer as mentioned below:
How to Install the ordered set module
By using the pip package installer download the ordered-set module as mentioned below
pip install ordered_set
Syntax of ordered Set:
orderedSet(Listname)
Now, for more clarification let's iterate the ordered set because the set cannot be iterated as mentioned below:
Python
from ordered_set import OrderedSet
createOrderedSet = OrderedSet(
['GFG', 'is', 'an', 'Excellent', 'Excellent', 'platform'])
print(createOrderedSet)
for item in createOrderedSet:
print(item, end=" ")
Output:
OrderedSet(['GFG', 'is', 'an', 'Excellent', 'platform'])
GFG is an Excellent platform
Using the Dictionary Data Structure
We can use the dictionary data structure to create the ordered set because the dictionary is itself the ordered data structure in which we will use set items as keys because keys are unique in the dictionary and at the place of value we can create the empty string. Let's take a look at implementation as explained below:
Python
d = {"Prince": "", "Aditya": "",
"Praveer": "", "Prince": "", "Shiv": ""}
print(d)
for key in d.keys():
print(key, end=" ")
Output{'Prince': '', 'Aditya': '', 'Praveer': '', 'Shiv': ''}
Prince Aditya Praveer Shiv
Using the list Data Structure
A list is a built-in data structure that stores an ordered collection of items. However, unlike a set, lists can contain duplicate values. To create an ordered set using a list, you need to manually remove duplicates while keeping the order of insertion intact. Let's take a look at implementation as explained below:
Python
def removeduplicate(data):
countdict = {}
for element in data:
if element in countdict.keys():
countdict[element] += 1
else:
countdict[element] = 1
data.clear()
for key in countdict.keys():
data.append(key)
dataItem = ["Prince", "Aditya", "Praveer", "Prince", "Aditya", "Shiv"]
removeduplicate(dataItem)
print(dataItem)
Output['Prince', 'Aditya', 'Praveer', 'Shiv']
Similar Reads
OrderedDict in Python
An OrderedDict is a dictionary subclass that remembers the order in which keys were first inserted. The only difference between dict() and OrderedDict() lies in their handling of key order in Python.OrderedDict vs dict in PythonNote: Starting from Python 3.7, regular dictionaries (dict) also maintai
9 min read
Python String Module
The string module is a part of Python's standard library and provides several helpful utilities for working with strings. From predefined sets of characters (such as ASCII letters, digits and punctuation) to useful functions for string formatting and manipulation, the string module streamlines vario
4 min read
Is List Ordered in Python
Yes, lists are ordered in Python. This means that the order in which elements are added to a list is preserved. When you iterate over a list or access its elements by index, they will appear in the same order they were inserted.For example, in a Python list:The first element is always at index 0.The
1 min read
Python MongoDB - Sort
MongoDB is a cross-platform document-oriented database program and the most popular NoSQL database program. The term NoSQL means non-relational. MongoDB stores the data in the form of key-value pairs. It is an Open Source, Document Database which provides high performance and scalability along with
2 min read
Python | sympy.as_ordered_terms() method
With the help of sympy.as_ordered_terms() method, we can get the terms ordered by variables by using sympy.as_ordered_terms() method. Syntax : sympy.as_ordered_terms() Return : Return ordered terms in mathematical expression. Example #1 : In this example we can see that by using sympy.as_ordered_ter
1 min read
sort() in Python
sort() method in Python sort the elements of a list in ascending or descending order. It modifies the original list in place, meaning it does not return a new list, but instead changes the list it is called on. Example:Pythona = [5, 3, 8, 1, 2] a.sort() print(a) a.sort(reverse=True) print(a)Output[1
4 min read
Python | sympy.compare() method
With the help of sympy.compare() method, we can compare the variables and it will return 3 values i.e -1 for smaller, 0 for equal and 1 for greater by using sympy.compare() method. Syntax : sympy.compare() Return : Return the value of comparison i.e -1, 0, 1. Example #1 : In this example we can see
1 min read
Insertion Sort - Python
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list.Insertion SortThe insertionSort function takes an array arr as input. It first calculates the length of the array (n). If the le
3 min read
Python reversed() Method
reversed() function in Python lets us go through a sequence like a list, tuple or string in reverse order without making a new copy. Instead of storing the reversed sequence, it gives us an iterator that yields elements one by one, saving memory. Example:Pythona = ["nano", "swift", "bolero", "BMW"]
3 min read
set() Function in python
set() function in Python is used to create a set, which is an unordered collection of unique elements. Sets are mutable, meaning elements can be added or removed after creation. However, all elements inside a set must be immutable, such as numbers, strings or tuples. The set() function can take an i
3 min read