How to Sort a List in Python (examples included)

You may use the following method in order to sort a list in Python in an ascending order (which is the default order):

yourlist.sort()

Alternatively, you may use this method to sort a list in a descending order:

yourlist.sort(reverse = True)

Next, you’ll see 4 cases of sorting a:

  1. List in an ascending order
  2. List in a descending order
  3. List of Lists
  4. List of Lists for a specific index

Case 1: Sort a List in Python in an Ascending Order

Let’s say that you created a simple list of names:

names = ['Jon','Maria','Bill','Liam','Emma']
print (names)

This is how the list would look like in Python:

Sort a list in Python

You can then sort the list of names in an ascending order by adding names.sort() to the code:

names = ['Jon','Maria','Bill','Liam','Emma']
names.sort()
print (names)

You’ll see that the list is now sorted in an ascending order, where Bill is the first name to be displayed, while Maria would be the last:

Example of names

Case 2: Sort a List in Python in a Descending Order

Alternatively, you could sort the list in a descending order by setting reverse = True as captured below:

names = ['Jon','Maria','Bill','Liam','Emma']
names.sort(reverse = True)
print (names)

Now Maria would be the first name, while Bill would be the last:

Names

Case 3: Sort a List of Lists

What if you have a list of lists?

For example, let’s say that you have the following dataset:

First NameLast NameAge
JonSmith21
MariaLee38
BillBrown42
LiamJones28
EmmaFord51

You can capture the above dataset in Python using a list of lists:

people_list = [['Jon','Smith',21],['Maria','Lee',38],['Bill','Brown',42],['Liam','Jones',28],['Emma','Ford',55]]
print (people_list)

This is how the list of lists would look like in Python:

How to Sort a List in Python (examples included)

You may then apply the following code to sort the list of lists in an ascending order:

people_list = [['Jon','Smith',21],['Maria','Lee',38],['Bill','Brown',42],['Liam','Jones',28],['Emma','Ford',55]]
people_list.sort()
print (people_list)

As you can see, the list of lists will now get sorted based on the first name:

Sort a List in Python

But what if you want to sort the list of lists on a different column?

In the final case below, you’ll see how to accomplish this goal.

Case 4: Sort a List of Lists for a Specific Column/Index

Suppose that you want to sort the list of lists based on the Age column (which has the index of ‘2’).

In that case, you may use lambda to sort the list of lists for a specific index:

people_list = [['Jon','Smith',21],['Maria','Lee',38],['Bill','Brown',42],['Liam','Jones',28],['Emma','Ford',55]]
people_list.sort(key = lambda i: i[2])
print (people_list)

Run the code, and you’ll see that indeed the list of lists is sorted based on Age:

Sort a list of lists in Python

You may also want to check the following guide that explains how to sort Pandas DataFrame.