some simple algorithms and data structures sorting in python the sorting algorithm used in most python implementations is called timsort the key idea is to take advantage of the fact that in lot of data sets the data is already partially sorted timsort' worst-case performance is the same as merge sort'sbut on average it performs considerably better as mentioned earlierthe python method list sort takes list as its first argument and modifies that list in contrastthe python function sorted takes an iterable object ( list or dictionaryas its first argument and returns new sorted list for examplethe code [ , , {' ': ' ': ' ':'dog'print sorted(lprint sort(print print sorted(dd sort(will print [ [ [ [' '' '' 'traceback (most recent call last)file "/current/mit/teaching/ /book/ algorithmsalgorithms py"line in sort(attributeerror'dictobject has no attribute 'sortnotice that when the sorted function is applied to dictionaryit returns sorted list of the keys of the dictionary in contrastwhen the sort method is applied to dictionaryit causes an exception to be raised since there is no method dict sort both the list sort method and the sorted function can have two additional parameters the key parameter plays the same role as compare in our implementation of merge sortit is used to supply the comparison function to be used the reverse parameter specifies whether the list is to be sorted in ascending or descending order for examplethe code [[ , , ]( , , , )'abc'print sorted(lkey lenreverse truesorts the elements of in reverse order of length and prints [( )[ ]'abc' timsort was invented by tim peters in because he was unhappy with the previous algorithm used in python