How to Sort a Set of Values in Python?

Published on Aug. 22, 2023, 12:15 p.m.

Sets in Python are unordered, and therefore don’t have a sort method like lists do. However, you can convert the set into a list and then sort it using the built-in sorted() function.

Here’s an example:

my_set = {4, 2, 1, 5, 3}
sorted_set = sorted(my_set)
print(sorted_set)

This will output:

[1, 2, 3, 4, 5]

Note that the sorted() function returns a new sorted list and does not modify the original set. If you need to convert the sorted list back into a set, you can use the set() function:

my_set = {4, 2, 1, 5, 3}
sorted_list = sorted(my_set)
sorted_set = set(sorted_list)
print(sorted_set)

This will output:

{1, 2, 3, 4, 5}

Tags: