When you work with python data,you will find yourself at one point or another needing to sort python list, based on some given criteria maybe. This simple guide will explain to you how you can go about this, based on the data type you are working with.
The first part of this simple sort python list guide will explain what we will be working with, and then the second part will now take a look at the available methods for sorting.
Another thing to note is that we will be using the built in python sorted method for this sorting in python mini-series.
Okay, if you are ready, let’s get started!
We will focus on basically sorting numbers and one of the most commonly used python data structures – dictionary.
Part one of this simple sort python list guide will introduce how sort works and the basics of it, by using a simple example.
Then, there will be Part two, that you can find in our Python tutorials, which will now dive deeper where we will learn hot to sort python list of python data structures – a list of dictionaries!
To be able to understand Part two of this guide - sorting python data structures - you need to understand how to sort a python list using python sorted method.
For that reason, we begin with a simple example:
simple_number_list = [1, 4, 3, 6, 2, 7, 10, 8, 9, 5]
This is some random number. So, you can sort it in two directions, either in ascending or descending order.
By default, python sorted method uses ascending sorting order. This is one thing to remember.
So:
sorted_list = sorted(simple_number_list)
print(sorted_list)
Will sort our list from smallest to the largest. The print method will display this:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Well, what if that is not our intention? Well, there is the reverse argument which we can pass into python sorted method and well, you guessed it right, reverse the sorting order.
sorted_list = sorted(simple_number_list, reverse=True)
print(sorted_list)
Now, the print method will display this:
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
By specifying:
reverse=True
you are telling the sorted method to:
So, you may wonder what:
reverse=False
would do, well, it would do nothing since that is the default.
Another IMPORTANT key takeaway from this brief introduction is that sorting does not happen in place, you will need to assign the results to another variable, or just the same variable, so that you can have the sorted list.
If you would have just had this:
simple_number_list = [1, 4, 3, 6, 2, 7, 10, 8, 9, 5]
sorted(simple_number_list, reverse=True)
print(sorted_list)
Then you would still have the original list, with no updates. So always remember, python sorted returns a new sorted list of what was passed into it.
Well, this concludes this simple introduction on how to sort python list. You have learnt:
Well, tune in for the next part of this tutorial, where we will be sorting a list of python data structures called dictionaries.
Happy Coding!