Sort numbers with python

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.

    return sorted(input, key=lambda x: abs(x))


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)


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]

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.

About the author

I currently work as a Test Automation Consultant at b.ignited. Here I work for different clients in different industries to help them start and speed up their testing cycles

I’ve been testing software since 2000 when I became involved in testing telephone applications and hardware. Since then, I’ve been able to expand my experience by testing a variety of embedded, web, mobile and desktop applications. I have used various development methodologies from waterfall to agile.

I consider myself to be a lifelong learner.