{"id":24001,"date":"2021-10-14T09:16:44","date_gmt":"2021-10-14T03:46:44","guid":{"rendered":"https:\/\/python-programs.com\/?p=24001"},"modified":"2021-11-05T16:49:21","modified_gmt":"2021-11-05T11:19:21","slug":"python-program-for-set-sorted-method","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-program-for-set-sorted-method\/","title":{"rendered":"Python Program for Set sorted() Method"},"content":{"rendered":"

In the previous article, we have discussed Python Program for Set remove() Method<\/a>
\nPython set:<\/strong><\/p>\n

Python set is a list of items that are not ordered. \u2013 Each element in the set must be unique and immutable, and duplicate elements are removed from the sets. Sets are mutable, which means they can be changed after they have been created.<\/p>\n

The elements of the set, unlike other Python sets, do not have an index, which means we cannot access any element of the set directly using the index. To get the list of elements, we can either print them all at once or loop them through the collection.<\/p>\n

Examples:<\/strong><\/p>\n

Example1:<\/strong><\/p>\n

Input:<\/strong><\/p>\n

Given set = {'hello', 'this', 'is', 'btechgeeks'}<\/pre>\n

Output:<\/strong><\/p>\n

The given set is :\r\n{'is', 'hello', 'btechgeeks', 'this'}\r\nThe given set after sorting the items in ascending order :\r\n['btechgeeks', 'hello', 'is', 'this']<\/pre>\n

Explanation:<\/strong><\/p>\n

Here the items of the set are sorted in ascending order based upon the ASCII values.<\/pre>\n

Example2:<\/strong><\/p>\n

Input:<\/strong><\/p>\n

 Given set = {2, 3, 5, 10, 6, 12, 50, 1}<\/pre>\n

Output:<\/strong><\/p>\n

The given set is :\r\n{1, 2, 3, 5, 6, 10, 12, 50}\r\nThe given set after sorting the items in descending order :\r\n[50, 12, 10, 6, 5, 3, 2, 1]<\/pre>\n

Explanation:<\/strong><\/p>\n

Here the items of the set are sorted in descending order using the reverse= True condition\r\n(based upon the ASCII values)<\/pre>\n

Program for Set sorted() Method in Python<\/h2>\n