How To Sort Numbers In Python

Sorting numbers is a common task in programming and Python offers various methods to do it. In this tutorial, we will learn how to sort numbers in Python using multiple techniques, including the sorted() function, sort() method, and sorting with lambda functions.

Step 1: Using the sorted() function

The sorted() function is a built-in Python function that allows you to sort a sequence of numbers in ascending or descending order. This function returns a sorted list and does not modify the original sequence.

Here’s an example:

Output:

[1, 9, 32, 34, 54, 67]

We can also sort the numbers in descending order by setting the reverse parameter to True.

Output:

[67, 54, 34, 32, 9, 1]

Step 2: Using the sort() method

The sort() method is a list method that sorts the elements of a list in ascending or descending order. This method sorts the list in-place and does not return a new sorted list. To use this method, call the sort() method on the list object.

Here’s an example:

Output:

[1, 9, 32, 34, 54, 67]

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

Output:

[67, 54, 34, 32, 9, 1]

Step 3: Sorting with lambda functions

In some cases, we may need to use custom sorting criteria. Python provides the key parameter in both sorted() function and sort() method, which allows you to specify a custom function to determine the sorting order.

Here’s an example of sorting a list of numbers based on their absolute values:

Output:

[-1, 9, 34, -32, 54, -67]

In this example, the key parameter evaluates each number’s absolute value and sorts the list based on that.

Full Code

Conclusion

In this tutorial, we have learned how to sort numbers in Python using the sorted() function, sort() method, and sorting with lambda functions. These methods give you flexibility in sorting sequences based on different criteria. It’s important to remember that the sorted() function returns a new sorted list, while the sort() method modifies the list in-place.