More info on sorted function

I’ve recently observed that Sorted(iterable, key=None, reverse=False) function can be used in almost every other situation, and with every data structure.
I want to know more about the implementation of this function, and use of parameter key in different situations, but I was unable to find much examples, tutorials about it.
I want you buddies to provide me with some links to the sorted function and other useful function which you think are not used commonly, but are useful…

The Python documentation is great:

Python Sorting HOWTO.

There is the method list.sort() which works on lists only (in place); sorted() works on any iterable (list, tuple, set, dict, etc.). They work similarly to the C language style sort functions by taking something to sort (iterable), directions on how to sort it (key), and which order (reverse).

Python is a little different and expects key to be a function (quite often a lambda, but it’s not necessary) that returns the part of one item in the complex iterable to use as the sorting key (like returning the family name from a list of full names) from which python infers how to sort, while the C language style is to have a function that takes two items, does a comparison defined by the function and returns a negative number (-1), 0, or a positive number (+1) to indicate lesser, equal, or greater. This behavior is still in python, it’s just not the default in sorted(). If you’re dealing with sortable objects in python, the class author often will define enough of the class comparison methods (__lt__(), __eq__(), etc.) to achieve sorting.

As far as the actual implementation of sorted(), I would assume the python source would be the first place to look. Its behavior is more complex than other implementations so if you just want to know about sorting, take a look at the sorting and hashing challenges in the Coding Interview Prep, especially the Algorithms section. Once you can implement those, think about how to take the integer comparison out of the algorithm and replace it with calls to a user defined comparison function. Once you can do that, you’ve got sorting under control.

1 Like

Thanks @JeremyLT and @jeremy.a.gray,
Though the official documentation must be the first place to look for info and it’s great, but I want to grab more knowledge.

I’ll surely start practicing this problems, to build a firm grip over concept of sorting, after all sorting is much basic as well as most used and important topic.

I wouldn’t overthink it. Think of it as a function you can use to sort an array of complex objects with multiple keys. If you ever need to sort such an array, you can look at the documentation and examples.

Based on your forum questions, you seem to know enough coding that you’ll run into special case functions like this every so often. Its normal to run into special use case high level functions.

1 Like