How to Use the Python List sort() Method

09/07/2021

Contents

In this article, you will learn how to use the Python list sort() method.

Python List sort() Method

The sort() method is a built-in function in Python that is used to sort the elements of a list in ascending order by default.

Here’s how you can use the sort() method:

list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
list.sort()
print(list)

//[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
 

The sort() method is a very useful tool in Python and has several additional parameters that you can use to customize the sorting process.

The reverse parameter allows you to sort the list in descending order. If you set reverse=True, the list will be sorted in descending order. The default value is False, which means that the list will be sorted in ascending order:

list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
list.sort(reverse=True)
print(list)

//[9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]
 

The key parameter allows you to specify a custom sorting function, which will be used to extract a value from each list item and determine their sort order. For example:

list = [{"name": "John", "age": 32}, {"name": "Jane", "age": 28}, {"name": "Jim", "age": 40}]
list.sort(key=lambda x: x["age"])
print(list)

//[{'name': 'Jane', 'age': 28}, {'name': 'John', 'age': 32}, {'name': 'Jim', 'age': 40}]
 

The cmp_to_key function is a utility function that converts an old-style comparison function to a key function. This can be useful when you want to sort a list using an older version of Python (2.x) where the key parameter was not yet available.

It’s important to note that the sort() method sorts the list in place and does not return a new sorted list. This means that the original list is modified and no copy is created. If you need to sort a list and keep the original list intact, you can use the built-in sorted() function, which returns a new sorted list.