How To Sort a Set in Python?

A set is one of the first elements that a Python user will approach in their learning adventure. It is an unindexed and unordered collection with no duplicate element at all. However, when we print out a set, it has a sorted display, but that is not the sorted list return that most of us want.

As a result, knowing how to sort a set in Python becomes a prerequisite for learning Python. This knowledge will serve as a base for you to build up other interesting features.

See full size

To Sort A Set In Python

Using The sorted()

This feature is an integrated part of Python, returning a sorted collection like dictionary, set, or sequence like tuple, string, list in a listed form. A special thing about this function is that it does not affect the original sequence at all.

After all, the returned list is newly created, so you can make use of the original sequence, too.

The sorted() function has a syntax as following: 

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

As you can clearly see, there are three input parameters.

  • iterable points to the input, either a collection or a sequence. Of course, any other iretator can fit in just as well.
  • reverse is an optional input, which decides how the list will be sorted. If you set it to True, the return list will be in descending order. This variable usually defaults to False if you don’t specify.
  • key is another optional input with a default value of None. You should only use it if there is a need to implement some specific requirements. A prime example is sorting sequences of 2 values based on the second value alone. In this case, you can assign the key variable with “getName”.

Here is an example on how this code works:

#Declare a list to sort
set_in_python = [(4,'David', 'D'), (1, 'Ana', 'A'), (3,'Cana', 'C'), (2,'Bom', 'B')]

#Sort by key
def getName(lst): 
    return lst[1]

#Set after being sorted
print('Ouput (ascending order):', sorted(set_in_python, key=getName,reverse=False))
print('Ouput (descending order):', sorted(set_in_python, key=getName,reverse=True))

The output would be as follows:

Ouput (ascending order): [(1, 'Ana', 'A'), (2, 'Bom', 'B'), (3, 'Cana', 'C'), (4, 'David', 'D')]
Ouput (descending order): [(4, 'David', 'D'), (3, 'Cana', 'C'), (2, 'Bom', 'B'), (1, 'Ana', 'A')]

Using The sort()

Another method that you can use is the sort() function. Unlike the sorted() method, this feature is more destructive, as it will be performed on the input list without creating a copy.

It also doesn’t work straight away with a set, as you need to enclose the set into a list first. You can either add in a pair of “[]” outside of the set, or you can use the list() function to complete this step.

The full syntax of this function is:

list.sort( key=…, reverse=…)

As you can see, the parameters also feature the same key and reverse variables. However, there is no iterable variable, as you call it directly. If we use the same example as the sorted() function, it becomes as follows:

#Declare a list to sort
set_in_python = [('David'), ('Ana'), ('Can'), ('Bo'), ('Enai')]

set_in_python.sort(key=len,reverse=True) #descending order

#Set after being sorted
print('Ouput:', set_in_python)

The output is the same as above.

Ouput: ['David', 'Enai', 'Ana', 'Can', 'Bo']

Conclusion

With this article, we have explained clearly how to sort a set in Python with two approaches. Each of them has its own unique strengths and weaknesses and can become the best solution under specific circumstances. Your job is to understand their characteristics and know when to use which option.

Leave a Reply

Your email address will not be published. Required fields are marked *