Python sort set | Example code

Use the sort() or sorted() method to sort the set in Python. As you know sets are unordered and it’s not possible to sort the values of a set but if we print a set, it is displayed in a sorted manner.

s = {5, 2, 7, 1, 8}

Output: {1, 2, 5, 7, 8}

Python sort set example

Simple example code uses the sort and sorted method.

Use the sorted() Function

This function returns a sorted sequence (list, tuple, string) or sorted collection(sets, dictionary) in the form of a list without changing original data.

s = {5, 2, 7, 1, 8}

n = sorted(s)


Output: As you can see output is a sorted list.

Python sort set

Use the sort() Method

It sorts the elements given in a list in ascending or descending order. It makes a change on the original list. You can’t use this method in the set.

s = {5, 2, 7, 1, 8}



Output: AttributeError: ‘set’ object has no attribute ‘sort’

However, you can enclose a set within a list, and it will sort them.

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



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

Do comment if you have any doubts and suggestions on this Python set tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.