Sometimes we need to sort numbers. In this post I will give a solution a fictive sorting problem. I want to sort numbers with python. Sorting is a part of many tasks. It is useful to know how to use the sorting function in python.
We have a list with positive and negative numbers. Create a function that sorts the list by the absolute values. This means without the sign.
Some examples will explain what I want to do:
- sorting [-20, -5, 10, 15] results in [-5, 10, 15, -20]
- sorting [1, 2, 3, 0] results in [0, 1, 2, 3]
- sorting [-1, -2, -3, 0] results in [0, -1, -2, -3]
My first solution uses the build in sorted function. Let’s create a function that has an input parameter and returns the sorted array. The sorted function has two input parameters. The first one is the list or iterable that you want to sort. The second one is a comparison key from each element in the list.
sort_numbers(input): return sorted(input, key=lambda x: abs(x)) sort_numbers([-1,-2,-4,0])
The sorted function will return a new array. The result is sorted according our rules. There is an other solution. A lambda function can be used.
sort_numbers=lambda n:sorted(n,key=abs) sort_numbers([-1,-2,-4,0])
The key can be just the abs function. There is no need to create an extra lambda.
A list object in python has a sort method. This method will modify the list in place. The output is the same.
the_numbers = [-1,-2,-4,0] the_numbers.sort(key=abs)
This solution is not the same as previous solution. The sort function on the list object modifies the original list object. The original list is not there anymore.
The sort function creates a new list object. To sort numbers with python is not difficult.