The 'sorted( )' Function is used to sort a Set in Ascending/Descending order.
At first let us see an example to sort a Set in Ascending order.
x = {"Mohan", "Kriti", "Salim"} sorted(x) print("The Sorted Set in ascending order is ",x)
So, in the above code we have created a 'Set' and initialised to the variable 'x'.
Then we have used the 'sorted( )' Function to sort the Set 'x' in ascending order.
And the Set 'x' gets sorted with 'Kriti' as the first value, 'Mohan' second and 'Salim' as the third.
And we get the below output.
Next let us see, how to sort a Set in Descending order.
x = {"Mohan", "Kriti", "Salim"} sorted(x,reverse = True) print("The Sorted Set in descending order is ",x)
So, in the above code we have created a 'Set' and initialised to the variable 'x'.
Then we have used the parameter 'reverse = True' and name of the set 'x' along with the 'sorted( )' method to sort the Set 'x' in descending order.
And the Set 'x' gets sorted in descending order with 'Salim' as the first value, 'Mohan' second and 'Kriti' as the third.
And we get the below output.
Even here the 'sorted( )' Function is used to sort a Set with numbers in Increasing/Deceasing Order.
At first let us see an example to sort a Set with numbers in Increasing order.
x = {5, 3, 2, 4} sorted(x) print("The Sorted Set in increasing order is ",x)
So, in the above code we have created a 'Set' and initialised to the variable 'x'.
Then we have used the 'sorted( )' method to sort the Set 'x' in increasing order.
And the numbers in the Set 'x' gets sorted.
And we get the below output.
Next let us see, how to sort a Set in Descending order.
x = {5, 3, 2, 4} sorted(x, reverse = True) print("The Sorted Set in decreasing order is ",x)
So, in the above code we have created a 'Set' and initialised to the variable 'x'.
Then we have used the parameter 'reverse = True' along with the 'sorted( )' method to sort the Set 'x' in decreasing order.
And the Set 'x' gets sorted in decreasing order.
And we get the below output.