Sorting Lists In Python

06 May 2014

How to do sorting in python?

Basically there are two built-in functions you can use: sort() and sorted().

sort() is called from a list object (therefore only defined for lists) and modifies the list in-place. If you don’t need the original list, this function is okay and slightly more efficient.

sorted() on the other hand is more convenient and accepts any iterable. It does not modify lists in-place, instead, it returns a new sorted list.

What’s even more useful is the above two functions allow mutiple levels of sorting. See examples from here. In case you’re wondering how the multiple level sorting is implemented: Timesort.