How to Sort Numbers in Python With the Sort Function

Sorting numbers or a list of any sort of data is a common task in programming. Python, being a general-purpose language, provides in-built functions to sort data. In this tutorial, we will be looking at the sort() function, which performs the task of arranging numbers in ascending or descending order in Python.

Understanding the Sort Function

The sort() function sorts the list ascending by default. If you want the function to sort descending, you just need to add the reverse parameter and set it to True i.e list.sort(reverse=True). The syntax of the sort function is as follows: list.sort([key=…], [reverse=…])

Note: The sort function modifies the list it is called on. If you want to sort a list but still keep the original order, you can use the sorted function.

Step 1: Creating a List of Numbers

Before sorting, we need to create a list of numbers. Here, we will create a list of unsorted numbers.

Step 2: Using the Sort Function

To sort the list we have created, we call the sort() function on it.

The code’s output would be:

[2, 3, 5, 6, 7, 8]

Step 3: Sorting in Descending Order

To sort the list in descending order, we pass the ‘reverse = True’ parameter.

And the output would be:

[8, 7, 6, 5, 3, 2]

The full code:

Conclusion

This tutorial explained how to use Python’s built-in sort() function to sort a list of numbers in either ascending or descending order, without the need for any additional libraries or complex algorithms. Remember, the sort() function changes the list it’s used on. If you need to maintain the original list’s order, use the sorted() function instead.