How To Sort A List In Python With Sort Function

Sorting a list is a common operation in Python programming. It helps in organizing the data in an orderly fashion, which leads to easier data manipulation and faster processing. In this tutorial, we will learn how to sort a list in Python using the sort function.

Step 1: Understand the sort method

Python provides a built-in method called sort() that can be applied to any list. The function sorts the elements in a list in ascending order by default. You can also sort the list in descending order or provide a custom sorting function if needed.

Here is the basic syntax:

  • reverse: A boolean value indicating whether to sort the list in ascending (False) or descending (True) order. The default value is False.
  • key: A custom sorting function that should return a value for each item in the list, based on which the list will be sorted. The default value is None, which means the list will be sorted based on the natural order of the elements.

Step 2: Sorting a simple list in ascending order

Create a simple list and use the sort() method to sort it in ascending order.

Output:

[5, 10, 45, 90, 140]

Step 3: Sorting a simple list in descending order

In order to sort the list in descending order, set the reverse parameter to True.

Output:

[140, 90, 45, 10, 5]

Step 4: Sorting a list of strings

Python can also sort lists containing strings with the sort() method. By default, the list will be sorted in alphabetical order.

Output:

['Annie', 'James', 'Nina', 'Sara', 'Tom']

Step 5: Sorting a list using a custom function as a key

Let’s say we have a list of dictionaries, and we want to sort these dictionaries based on a specific key. We can define a custom function that returns the value used for sorting.

Output:

[{'name': 'James', 'age': 19}, {'name': 'Sara', 'age': 20}, {'name': 'Nina', 'age': 22}, {'name': 'Tom', 'age': 23}]

Full Code

Conclusion

In this tutorial, we learned how to sort a list in Python using the built-in sort() method. We covered how to sort a simple list, a list of strings, and a more complex list including dictionaries. With these methods, you can easily organize your data and make it more accessible for further processing.