Lists can be sorted alphanumerically in either ascending (by default) or descending order. To do this, we use the sort()
method.
sort(reverse)
The sort()
method takes a single optional parameter value, reverse
. This parameter could have a value of False
(by default) or True
.
When reverse = False
, we are simply telling Python to return a list arranged in ascending order, while when reverse = True
, we are telling Python to return the list in descending order.
The sort()
function returns a list arranged in either ascending or descending order.
We will create two lists, one with a string data type and the other with a number type, and sort it alphabetically and numerically, respectively, in ascending order, by using the sort()
function.
# creating a list with string typemylist1 = ["apple", "orange", "lemon", "pineapple", "cherry"]# creating a numerical listmylist2 = [5, 2, 3, 1, 4]# implementing the sort() functionmylist1.sort()mylist2.sort()# printing our listsprint(mylist1)print(mylist2)
We can see that we are able to sort the lists mylist1
and mylist2
alphabetically and numerically, respectively, in ascending order by simply using the sort()
function.
By default, when we don’t pass a value to the
reverse
parameter insort()
, it automatically sets toFalse
, and returns the list in ascending order.
We will create two lists, one with a string data type and the other with a number type, and sort it alphabetically and numerically, respectively, in descending order by using the sort()
function and passing the parameter reverse
as False
.
# creating a list with string typemylist1 = ["apple", "orange", "lemon", "pineapple", "cherry"]# creating a numerical listmylist2 = [5, 2, 3, 1, 4]# implementing the sort) function to create a descending ordermylist1.sort(reverse = True)mylist2.sort(reverse = True)# printing our listsprint(mylist1)print(mylist2)
We can see that we are able to sort the lists mylist1
and mylist2
alphabetically and numerically, respectively, in descending order, by simply using the sort()
function and passing its parameter value reverse
as True
.