Python List - sort method

Sort the elements in a python list object either with the single paramter key function or using the default behaviour

List Updated 15 Sep 2016 2 min read

sort(key=None, reverse=False)

Method Overview

The sort() function performs a stable, in-place sorting.

In-Place sorting is the sorting method without need to allocate auxiliary space.

e.g. To sort one array internally you create a new array and start filling that new array with sorted elements.

However, some constant space will be used internally for operations like swapping.

Stable Sorting is when you get the elements with same values to appear in the same order in the output array as they were in the input array.

The key function or the Single Parameter Comparison function is of the form that takes one parameter and returns one parameter.

If defined and provided, the key function is called for each element in the python list object that is being sorted. The key function transforms

each element in the python list object before it is supplied for the sorting function.

This method does not return anything. The array is just transformed as per the sorting rules provided in the

method signature. In case, if you do not want the original list to be transformed, you can use the similar function

sorted() which does not change the original python list.

Exceptions

None

Example1: Sorting a Python list Default Sorting

python
>>> IntegerList = [64,56,8,16,16,40,32,48]

            >>> IntegerList.sort()

            >>> print(IntegerList)

            [8, 16, 16, 32, 40, 48, 56, 64]

Example 2: Sorting a Python list with a key function

python
>>> StringList=["Python","Java","C++","Ruby","Scala"]

            >>> StringList.sort(key=str.upper)

            >>> print(StringList)

            ['C++', 'Java', 'Python', 'Ruby', 'Scala']

The above example just treats all the strings same way because each of the strings were transformed before sorting.

Example 3: Sorting a Python list with a custom key function defined

python
>>> def customKeyFunction(input):

            ...     return ord(input[0])+ord(input[1])

            ...

            >>> StringList.sort(key=customKeyFunction)

            >>> print(StringList)

            ['C++', 'Java', 'Scala', 'Ruby', 'Python']

In the above example, a custom key function is defined, which returns the sum of ASCII values of the first two characters
of the strings in the list. The list is sorted as per this custom key function.