Sort a Set in Python

Sort a Set in Python

  1. Use the sorted() Function to Sort a Set in Python
  2. Use the sort() Method to Sort a Set in Python

Sets are an unordered and unindexed collection having no duplicate elements. Sets are one of the four built-in data types available in Python and are written using curly brackets.

Given that sets are unordered, it is not possible to sort the values of a set. However, if we print a set, it is displayed in a sorted manner.

See the code below.

s = {5,2,7,1,8}
print(s)

Output:

{1, 2, 5, 7, 8}

If we want, we can use different functions will sort a set and return a list. These are discussed below.

Use the sorted() Function to Sort a Set in Python

The sorted() function is a built-in function in Python that returns a sorted sequence (list,tuple,string) or sorted collection(sets,dictionary) in the form of a list. The sorted() function has no effect on the original iterable sequence as it provides a new sorted output.

For example,

s = {5,2,7,1,8}
print(sorted(s))

Output:

[1, 2, 5, 7, 8]

Note that the sorted() function returns a list instead of a set. We can again convert this list to a set using the set() function. However, this is redundant since sets are unordered.

Use the sort() Method to Sort a Set in Python

The sort() Method is used to sort the elements given in a list in ascending or descending order. It is a destructive process, i.e., unlike the sorted() function, the sort() method sorts the elements in the original list itself.

We cannot use this function with a set. However, we can enclose a set within a list, and it will sort them.

For example,

s = [{5,2,7,1,8}]
s.sort()
print(s)

Output:

[{1, 2, 5, 7, 8}]

Note that the sort() function also returns the final output in a list. We can take a similar approach with the sorted() function also.

On the other hand, we can convert the set to a list using the list() function and sort it with this method.

See the code below.

s = {5,2,7,1,8}
l = list(s)
l.sort()
print(l)

Output:

[1, 2, 5, 7, 8]