Deepjyoti Barman
Posted on April 12, 2020
Python has a lot of applications, from chatbots to API's, we have a module for almost everything. But in order to get the most out of it, we should know the basics. One of the basic things in a language that is used almost every now and then is sorting. Here's how to use sorting in Python using the prebuilt methods.
Options
- sorted()
- .sort()
sorted()
The method that even the Python docs suggest is sorted. Under the hood, Python uses timsort.
Timsort is a hybrid sorting algorithm, derived from merge sort and insertion sort, designed to perform well on many kinds of real-world data.
[Here's] a better explanation.
The method takes just a few arguments.
sorted(iterable, *, key=None, reverse=False)
It's pretty straightforward to understand the arguments.
iterable
Iterable is any datatype that can be iterated or looped over. Python currently supports tuple, list, or dictionaries.
d = [1, 2, 3, 4, 5]
# Sort using the sorted method
d = sorted(d)
key
Key is a function that takes one argument. Each element that is got while iterating over the iterable is passed as an argument to this function.
The return value of this function is used to compare where the passed arguments position should be.
The default value is None.
d = [
[2, "second"],
[3, "third"],
[-1, "first"]
]
# Function to return the zeroth element in each
# object
def getzeroth(el):
return el[0]
# Sort the dictionary by using the 0th
# element in each object.
d = sorted(d, key=getzeroth)
NOTE: We can also use a lambda function instead of defining a whole function.
# Sort using the zeroth element using a lambda
# function
d = sorted(d, key=lambda x: x[0])
reverse
This argument just takes a bool as argument and the default value is False. If True is passed then the result will be reversed, i:e the iterable will be sorted in descending order.
d = [1, 2, 3]
# Make the list reverse ordered
d = sorted(d, reverse=True)
.sort()
The sort method sorts the list in place. It is a method of the list class itself so it takes one argument less than sorted. Just like sorted this method uses Timsort under the hood.
This method is usually simpler to use with lists.
The arguments passed are:
sort(*, key=None, reverse=False)
Just like sorted we can pass key and reverse in this method as well.
d = [1, 5,27, 89, -90]
# Sort the list using .sort
d.sort()
This article was aimed at those who are new to Python or even advanced Python programmers but need some kind of a bookmarkable post to look at the sorting methods in Python.
I also write at my personal site https://deepjyoti30.github.io/ about Python, technology and other stuff. Do check it out.
Posted on April 12, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.