How to sort a list in ascending or descending order in Python

Overview

Lists can be sorted alphanumerically in either ascending (by default) or descending order. To do this, we use the sort() method.

Syntax

sort(reverse)

Parameter

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.

Return value

The sort() function returns a list arranged in either ascending or descending order.

Example 1: 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 ascending order, by using the sort() function.

Code

# creating a list with string type
mylist1 = ["apple", "orange", "lemon", "pineapple", "cherry"]
# creating a numerical list
mylist2 = [5, 2, 3, 1, 4]
# implementing the sort() function
mylist1.sort()
mylist2.sort()
# printing our lists
print(mylist1)
print(mylist2)

Code explanation

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 in sort(), it automatically sets to False, and returns the list in ascending order.

Example 2: 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 descending order by using the sort() function and passing the parameter reverse as False.

Code

# creating a list with string type
mylist1 = ["apple", "orange", "lemon", "pineapple", "cherry"]
# creating a numerical list
mylist2 = [5, 2, 3, 1, 4]
# implementing the sort) function to create a descending order
mylist1.sort(reverse = True)
mylist2.sort(reverse = True)
# printing our lists
print(mylist1)
print(mylist2)

Code explanation

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.

Free Resources