How to Sort Lists in Python

Posted on
How to Sort Lists in Python

This article will teach you how to sort a list in Python.

In Python, you can use the sort() method to sort a list in place. Or you can use the built-in sorted() function to get a sorted copy of the list.

In this tutorial, you’ll learn:

  • Syntax of the sort() method and the sorted() function
  • Code examples of sorting lists in ascending and descending order
  • Customize sort using the key parameter
  • Difference between sort() vs sorted()

Let’s start!??‍?

Syntax of Python sort() Method

The sort() method acts on a Python list. And it sorts the list in place—and modifies the original list.

The syntax for Python’s sort() method is:

.sort(reverse = True | False, key = )

Let’s now parse the above syntax.

  • is any valid Python list object.
  • reverse is an optional parameter that takes either True or False.
  • The default value of reverse is False, and the list is sorted in ascending order. Give True to sort the list in descending order.
  • key is also an optional parameter that’s set to .
  • can be a built-in function or a user-defined function.

In the next section, you’ll start coding simple examples.

How to Sort Python List in Ascending Order

Consider the list nums. To sort the list in ascending order, you can call the sort() method on the list.

▶ Run the following code snippet.

nums = [25,13,6,17,9]
nums.sort()
print(nums)

# Output: [6, 9, 13, 17, 25]

The list nums has been sorted in ascending order, and the original list has been modified. This is called in-place sorting.

How to Sort Python List in Descending Order

To sort the list in descending order, set reverse to True, as shown below.

nums = [25,13,6,17,9]
nums.sort(reverse = True)
print(nums)

# Output: [25, 17, 13, 9, 6]

You can see that the list is now sorted in descending order.

How to Use key with Python sort() Method

In this section, let’s use the key parameter and customize the sort.

Here, mod5() is a function that takes in a number x, and returns the remainder when the number x is divided by 5.

def mod5(x):
  return x % 5 

And we’d like to use the above function as the key.

Now, run the following code cell.

nums = [25,13,6,17,9]
nums.sort(key = mod5)
print(nums)

# Output: [25, 6, 17, 13, 9]

Take a minute to parse the output.

Notice how instead of the regular sorting, you are now customizing your sort according to the key which is mod5.

  • The number that leaves the minimum remainder when divided by 5 comes first now.
  • And the number that leaves the largest remainder when divided by 5 is the last element in the sorted list.

To verify this is the case, run the following code snippet.

nums = [25,13,6,17,9]

for num in nums:
  print(f"{num} leaves remainder {num%5} when divided by 5")

# Output
25 leaves remainder 0 when divided by 5
13 leaves remainder 3 when divided by 5
6 leaves remainder 1 when divided by 5
17 leaves remainder 2 when divided by 5
9 leaves remainder 4 when divided by 5

5 divides 25 exactly, and the remainder is 0. So that’s the first element in the sorted list. 6 leaves a remainder 1, so it’s the second element, and so on. 9 leaves the remainder 4 when divided by 5, and it’s the last element in the sorted list.

Instead of defining a separate function, you might as well use lambda functions. In Python, lambdas are one-line anonymous functions. lambda args : expression returns the expression computed on the args.

Now, let’s rewrite the above sort using the lambda expression, as shown below.

nums = [25,13,6,17,9]
nums.sort(key = lambda x:x%5)
print(nums)

# Output: [25, 6, 17, 13, 9]

So far, you’ve learned how to sort a list of numbers. Next, let’s see how you can sort a list of strings in Python.

How to Sort Python List in Alphabetical Order

In this section, you’ll learn to sort a list of strings—with examples inspired by Harry Potter. ✨

python-sort-list

In our example, students is a list of students at Hogwarts. And we’d like to sort them in the alphabetical order of their names.

When sorting a list of strings, the default sorting is in alphabetical order.

students = ["Harry","Ron","Hermione","Draco","Cedric"]

Let’s print out the sorted list to verify the result of sorting.

students.sort()
print(students)

# Output
['Cedric','Draco', 'Harry', 'Hermione', 'Ron']

How to Sort Python List in Reverse Alphabetical Order

In order to sort the list in reverse alphabetical order, set reverse = True, as shown in the code snippet below.

students.sort(reverse = True)
print(students)

# Output
['Ron', 'Hermione', 'Harry', 'Draco', 'Cedric']

From the output, you can see that the list has indeed been sorted in reverse order.

How to Use key Parameter Customize Sort

In this section, let’s customize the sort using the optional key parameter.

Consider the following list, houses.

houses = [
            {1:"Draco","house":"Slytherin"},
            {2:"Harry","house":"Gryffindor"},
            {3:"Cedric","house":"Hufflepuff"}
         ]

Here, houses is a list of dictionaries. Each dictionary contains two key-value pairs, one denoting the students’ names and the other the house to which they belong.

Now, we would like to sort this list houses in the alphabetical order of houses they belong to.

As you might have guessed by now, we should set the key parameter to the house of the particular students.

In order to retrieve the house of each student, you can define a function returnHouse(), as shown below.

def returnHouse(student):
  return student['house']

This function returns the house to which the particular student belongs.

Now, you can call the sort() method on the houses list, as shown.

houses.sort(key=returnHouse)

In the output below, notice how the list is sorted by the house and not the students’ names. That’s why we have Gryffindor, Hufflepuff, and Slytherin—in alphabetical order.

print(houses)

# Output
[{2: 'Harry', 'house': 'Gryffindor'}, 
{3: 'Cedric', 'house': 'Hufflepuff'}, 
{1: 'Draco', 'house': 'Slytherin'}]

To define the key parameter accordingly, you could also use a lambda function. For every list item, this function returns the house for that list item.

▶ Run the following code cell to verify this.

houses.sort(key=lambda student:student["house"])
print(houses)

# Output
[{2: 'Harry', 'house': 'Gryffindor'}, 
{3: 'Cedric', 'house': 'Hufflepuff'}, 
{1: 'Draco', 'house': 'Slytherin'}]

In all the examples so far, you’ve used the sort() method on a list. And you now know that it modifies the original list.

What if you’d like to retain the original list as it is but obtain a sorted copy of the list?

Well, in Python, you can use the sorted() function to do this.

Syntax of Python sorted() Function

The sorted() function takes in a list or any collection as the argument. And it returns a sorted copy of the list—and the original list is not modified.

The syntax for Python’s sorted() function is:

 = sorted(, reverse = True | False, key = )

Notice how the syntax is very similar to the sort() method we saw earlier.

  • is any valid Python list object and is a required parameter.
  • reverse and key are optional parameters

Note: Unlike the sort() method that acts only on lists, sorted() function can be used to sort any Python iterable, such as lists, strings, and dictionaries.

How to Sort Python List Using sorted() Function

#1. In this example, nums is a list of numbers.

You can call the sorted() function with nums as the argument. And assign it to the list sorted_nums1.

nums = [25,13,6,17,9]
sorted_nums1 = sorted(nums)
print(sorted_nums1)

# Output: [6, 9, 13, 17, 25]

In the output above, you can see that nums has been sorted in ascending order by default.

Also, notice that the original list nums is not modified—because sorted() returns a new list. This is verified below.

print(nums)
 # Output: [25, 13, 6, 17, 9]

#2. Now, set the optional parameter reverse to True and get sorted_nums2.

As shown in the code cell below, sorted_nums2 is a new list with the items sorted in the descending order.

sorted_nums2 = sorted(nums,reverse = True)
print(sorted_nums2)

# Output: [25, 17, 13, 9, 6]

#3. In this example, let’s work with a list of strings.

As with the previous examples, calling the sorted() function returns a new list. And the items are sorted in alphabetical order.

fruits = ['pears','strawberry','apple','pineapple','blueberry']
sorted_fr1 = sorted(fruits)
print(sorted_fr1)

# Output:
['apple', 'blueberry', 'pears', 'pineapple', 'strawberry']

#4. Now, let’s customize the sort using the optional key parameter. Set the key to len. This will sort the list based on the length of the strings.

Note: In Python, the built-in len() function takes in any iterable, such as lists, string, tuples, and so on. And it returns the length of the iterable.

The string with the shortest length appears first in the sorted list, and the longest string appears at the end of the sorted list.

fruits = ['pear','strawberry','apple','pineapple','blueberry']
sorted_fr2 = sorted(fruits,key=len)
print(sorted_fr2)

# Output:
['pear', 'apple', 'pineapple', 'blueberry', 'strawberry']

In the output above, pear is the shortest string, and strawberry is the longest string. 

Python sort() Method vs. sorted() Function

So far, you’ve learned how to use the sort() method as well as the sorted() function. In this section, let’s enumerate the differences between these two methods.

Python .sort() Method Python sorted() Function
Sorts the list in place—modifies the original list Returns a new sorted list
Works only with Python lists Works with Python iterables such as lists, strings, and other collections
Has return type of None Returns a sorted copy of the iterable

Summing Up ?‍?

I hope you found this Python lists tutorial helpful.

Let’s quickly summarize what we’ve covered.

  • Use list.sort(reverse = True | False, key = ) with the optional reverse and key parameters to sort a list in place.
  • Use sorted(list, reverse = True | False, key = ) to get a sorted copy of the list.

Now that you’ve learned how to sort Python lists, learn about list comprehension in Python. Or you could as well learn how to handle files or work with JSON files in Python.

You may try the examples given above in the Geekflare Online Python Compiler.