Sort a Set in Python

To sort a Python set, use either the sorted() or sort() function. In this tutorial, we will go through examples of how to use both of these functions.

 

How to use the Python sorted() function

Here is the syntax of the Python sorted() function:

 

sorted(iterable, key=key, reverse=reverse)

 

  • iterable – The iterable to sort (required).
  • key – a function to run that changes the behaviour of the sorting (optional).
  • reverse – boolean value to control sorting direction, True is reverse. Default is False (optional).

 

Python Sorted Set Example

The example below demonstrates sorting a set of numbers into ascending order:

 

s = {11,5,7,1,9}
print(sorted(s))
[1, 5, 7, 9, 11]

 

sorted() returns a list, to convert it back to a set use the set() function like this:

 

s = {11,5,7,1,9}
print(set(sorted(s)))
{1, 5, 7, 9, 11}

 

Sort a Set in Descending Order Example

Here is another example, this time sorting a set into descending order using the reverse attribute in the sorted() function:

 

s = {11,5,7,1,9}
res = sorted(s, reverse=True)
print(res)
[11, 9, 7, 5, 1]

 

Note - If you convert the result back to a set after completing the descending order operation it will automatically revert back to ascending order.

 

Sort a Set with the Python set() Function

The sort() function only works with lists. To get around this, we can wrap the set() in list tags before sorting. The sort() function is destructive as it modifies the original list.

 

s = {11,5,7,1,9}
[s].sort()
print(s)
{1, 5, 7, 9, 11}

 

The advantage of using sort() is the result doesn't need to be converted back to a set:

 

s = {11,5,7,1,9}
[s].sort()
print(type(s))
<class 'set'>