To sort the items of a set in Python, you can convert the set to a list and then sort the list using the sorted()
function.
In this example,
numbers
containing some integer elements using curly braces {}
.list()
constructor.sorted()
function and store the result in sorted_numbers
.numbers = {5, 3, 1, 4, 2}
sorted_numbers = sorted(list(numbers))
print('Sorted numbers:')
for number in sorted_numbers:
print(number)
Sorted numbers: 1 2 3 4 5
In this example,
fruits
containing some string elements using curly braces {}
.list()
constructor.sorted()
function and store the result in sorted_fruits
.fruits = {'Banana', 'Apple', 'Cherry', 'Date'}
sorted_fruits = sorted(list(fruits))
print('Sorted fruits:')
for fruit in sorted_fruits:
print(fruit)
Sorted fruits: Apple Banana Cherry Date
In this tutorial, we learned How to Sort Items of a Set in Python language with well detailed examples.