python' built-in sorting functions python provides two built-in ways to sort data the first is the sort method of the list class as an examplesuppose that we define the following listcolors red green blue cyan magenta yellow that method has the effect of reordering the elements of the list into orderas defined by the natural meaning of the operator for those elements in the above examplewithin elements that are stringsthe natural order is defined alphabetically thereforeafter call to colors sort)the order of the list would becomeblue cyan green magenta red yellow python also supports built-in functionnamed sortedthat can be used to produce new ordered list containing the elements of any existing iterable container going back to our original examplethe syntax sorted(colorswould return new list of those colorsin alphabetical orderwhile leaving the contents of the original list unchanged this second form is more general because it can be applied to any iterable object as parameterfor examplesortedgreen returns sorting according to key function there are many situations in which we wish to sort list of elementsbut according to some order other than the natural order defined by the operator for examplewe might wish to sort list of strings from shortest to longest (rather than alphabeticallyboth of python' built-in sort functions allow caller to control the notion of order that is used when sorting this is accomplished by providingas an optional keyword parametera reference to secondary function that computes key for each element of the primary sequencethen the primary elements are sorted based on the natural order of their keys (see pages and of section for discussion of this technique in the context of the built-in min and max functions key function must be one-parameter function that accepts an element as parameter and returns key for examplewe could use the built-in len function when sorting strings by lengthas call len(sfor string returns its length to sort our colors list based on lengthwe use the syntax colors sort(key=lento mutate the list or sorted(colorskey=lento generate new ordered listwhile leaving the original alone when sorted with the length function as keythe contents arered blue cyan green yellow magenta these built-in functions also support keyword parameterreversethat can be set to true to cause the sort order to be from largest to smallest