The 'sort( )' Function is used to sort a List in Ascending/Descending order.
x = ["Mohan", "Kriti", "Salim"] x.sort() print("The Sorted List in ascending order is ",x)
So, in the above code we have created a 'List' and initialised to the variable 'x'.
Below is how the values are positioned in the List,
Then we have used the 'sort( )' method to sort the List 'x' in ascending order.
And the List 'x' gets sorted with 'Kriti' as the first value, 'Mohan' second and 'Salim' as the third.
And we get the below output.
x = ["Mohan", "Kriti", "Salim"] x.sort(reverse = True) print("The Sorted List in descending order is ",x)
So, in the above code we have created a 'List' and initialised to the variable 'x'.
Below is how the values are positioned in the List,
Then we have used the parameter 'reverse = True' along with the 'sort( )' method to sort the List 'x' in descending order.
And the List '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.
Also it is a better option to convert the elements in the List in lower case. So the case sensitive problems don't occur.
We can just use the parameter 'key = str.lower' with the 'sort( )' Function.
Let the see the example to sort in Ascending order.
x = ["Mohan", "Kriti", "Salim"] x.sort(key = str.lower) print("The Sorted List in ascending order is ",x)
Even here, the 'sort( )' Function is used to sort a List with numbers in Increasing/Deceasing Order.
At first let us see an example to sort a List with numbers in Increasing order.
x = [5, 3, 2, 4] x.sort() print("The Sorted List in increasing order is ",x)
So, in the above code we have created a 'List' and initialised to the variable 'x'.
Below is how the values are positioned in the List,
Then we have used the 'sort( )' method to sort the List 'x' in increasing order.
And the numbers in the List 'x' gets sorted.
And we get the below output.
x = [5, 3, 2, 4] x.sort(reverse = True) print("The Sorted List in decreasing order is ",x)
So, in the above code we have created a 'List' and initialised to the variable 'x'.
So, in the above code we have created a 'List' and initialised to the variable 'x'.
Below is how the values are positioned in the List,
Then we have used the parameter 'reverse = True' along with the 'sort( )' method to sort the List 'x' in decreasing order.
And the List 'x' gets sorted in decreasing order.
And we get the below output.