Custom Sorting in Python

Posted on the 16 October 2011 by Skiabox @skiabox

A classic way in python to sort a list is by using the sort() function.

For example if we have a list

>>> x = [3, 8, 4, 2, 9]

...we can use sort() like this...

>>> x.sort()

>>> x

[2, 3, 4, 8, 9]

As you can see our list is now sorted.

This function works with strings too.

So here is another example, this time using strings instead of numbers :

>>> x = ["This", "Is", "My", "Sample", "Phrase"]

>>> x.sort()

>>> x

['Is', 'My', 'Phrase', 'Sample', 'This']

Here again the sort() function compares the strings and put them succefully in order.

From python version 2.4 and beyond we can use our own key function to determine how elements of a list are sorted.

Here is a program that does exactly that.

----------------------------------------------------------
#define function
def compare_num_of_chars(string1):
    return len(string1)

#first output
word_list = ['This', 'is', 'a', 'sample', 'paragraph']

word_list.sort()

print(word_list)

#second output
word_list = ['This', 'is', 'a', 'sample', 'paragraph']

word_list.sort(key=compare_num_of_chars)

print(word_list)
----------------------------------------------------------

And here is the produced output :

['This', 'a', 'is', 'paragraph', 'sample']

['a', 'is', 'This', 'sample', 'paragraph']

The first line of our output does the classic sorting by comparing the strings.

In the second paragraph we have a sorting based on string length.

To achieve that we define a simple function that takes a list element as argument and returns its length.

Then we use the enhanced sort(key=function_name) function

(replacing function_name with our key function name , in this case compare_num_of_chars)