How to Sort a List in Python

To sort a List in Python in an ascending order:

my_list.sort()

To sort a List in a descending order:

my_list.sort(reverse=True)

4 Cases of Sorting a List

Case 1: Sort a List in an Ascending Order

To start, create a List of names:

names = ["Jon", "Maria", "Bill", "Liam", "Emma"]

print(names)

The resulted List:

['Jon', 'Maria', 'Bill', 'Liam', 'Emma']

To sort the List of names in an ascending order using names.sort():

names = ["Jon", "Maria", "Bill", "Liam", "Emma"]

names.sort()

print(names)

The List is now sorted in an ascending order, where “Bill” is the first name, while “Maria” is the last:

['Bill', 'Emma', 'Jon', 'Liam', 'Maria']

Case 2: Sort a List in a Descending Order

Alternatively, sort the List in a descending order by setting reverse=True:

names = ["Jon", "Maria", "Bill", "Liam", "Emma"]

names.sort(reverse=True)

print(names)

Now “Maria” is the first name, while “Bill” is the last:

['Maria', 'Liam', 'Jon', 'Emma', 'Bill']

Case 3: Sort a List of Lists

Suppose that you have the following List of Lists:

people_list = [
["Jon", "Brazil", 21],
["Maria", "Iceland", 38],
["Bill", "Spain", 42],
["Liam", "Japan", 28],
["Emma", "Italy", 51],
]

print(people_list)

The resulted List of Lists:

[['Jon', 'Brazil', 21], ['Maria', 'Iceland', 38], ['Bill', 'Spain', 42], ['Liam', 'Japan', 28], ['Emma', 'Italy', 51]]

To sort the List of Lists in an ascending order:

people_list = [
["Jon", "Brazil", 21],
["Maria", "Iceland", 38],
["Bill", "Spain", 42],
["Liam", "Japan", 28],
["Emma", "Italy", 51],
]

people_list.sort()

print(people_list)

As you can see, the List of Lists is sorted based on the first name:

[['Bill', 'Spain', 42], ['Emma', 'Italy', 51], ['Jon', 'Brazil', 21], ['Liam', 'Japan', 28], ['Maria', 'Iceland', 38]]

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

To sort the List of Lists based on the “Age” column (which has the index of “2“):

people_list = [
["Jon", "Brazil", 21],
["Maria", "Iceland", 38],
["Bill", "Spain", 42],
["Liam", "Japan", 28],
["Emma", "Italy", 51],
]

people_list.sort(key=lambda i: i[2])

print(people_list)

The List of Lists is now sorted based on the “Age”:

[['Jon', 'Brazil', 21], ['Liam', 'Japan', 28], ['Maria', 'Iceland', 38], ['Bill', 'Spain', 42], ['Emma', 'Italy', 51]]

Check the following guide that explains how to sort Pandas DataFrame.

Leave a Comment