Skip to content

Python sort set | Example code

  • by

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}
print(s)

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

Python sort set an example

A 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 the original data.

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

n = sorted(s)

print(n)

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 to the original list. You can’t use this method in the set.

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

s.sort()

print(s)

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}]

s.sort()

print(s)

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

Please comment if you have any doubts or suggestions on this Python set tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading