Sorting is an important feature of any programming language. Having a large set of data that you can’t sort and have to check values one by one wouldn’t get you very far.
There is a large number of sorting algorithms to which I was first introduced in (in my opinion) one of the best online courses, Harvard’s CS50 Introduction to Computer Science.
Sorting algorithms is a huge topic that I want to explore further in the future. I believe understanding here is very useful when building complex programs where performance is key, but for everyday programs Python’s built-in sorted() function is probably more than enough when one needs to sort an iterable. I’m not really familiar what algorithm it uses and its performance, but that’s for future exploration.
You can sort simple iterable (list, tuple, string) very quickly like this, but note that result is a List:
|
|
To reverse the order, add second argument into sorted, reverse=True.
|
|
Sorting complex Iterables
Let’s say you are working with a bit more complex iterable, such as a List with dictionaries.
|
|
What if you want to sort the list according to the age in the dictionary? Simple, you can use sorted() again and pass another argument, this time the argument must be a function. Using one-line lambda function is very effective here.
|
|
This is another nice feature of Python. As mentiond before, large and complex data would probably benefit more from different sorting algorithms, but that’s the topic I still need to explore a lot more.