How to sort a set in Python?


Python - Sort a Set

To sort a set of items in Python, you can use sorted() built-in function. Call sorted() function and pass the given set as argument. The sorted() method sorts the items in the given set and returns as a list.

Examples

1. Sort a set of numbers in Python

In this example, we take a set of numbers in nums variable, and sort the numbers in the set using sorted() built-in function.

Python Program

nums = {30, 50, 40, 10, 20, 70, 60}
print(f"Given numbers  : {nums}")

sorted_nums = sorted(nums)
print(f"Sorted numbers : {sorted_nums}")

Output

Given numbers  : {50, 20, 70, 40, 10, 60, 30}
Sorted numbers : [10, 20, 30, 40, 50, 60, 70]

2. Sort a set of strings in Python

In this example, we take a set of numbers in nums variable, and sort the numbers in the set using sorted() built-in function.

Python Program

strings = {"banana", "fig", "apple", "cherry"}
print(f"Given set    : {strings}")

sorted_strings = sorted(strings)
print(f"Sorted items : {sorted_strings}")

Output

Given set    : {'apple', 'fig', 'banana', 'cherry'}
Sorted items : ['apple', 'banana', 'cherry', 'fig']

Summary

In this tutorial of Python Sets, we have seen how to sort a set of items using sorted() built-in function, with examples.