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}")
Run Code Copy

Output

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

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}")
Run Code Copy

Output

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

Summary

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

Related Tutorials

Code copied to clipboard successfully 👍