Sort list of list with custom compare function in Python

In this tutorial, we will get to know how to sort a list with a custom compare function in Python. In Python, there are in-built functions to sort a list. But, sometimes we need to sort a list using a custom comparator code. So, if you want to know how to sort a list on the basis of your own comparator function you are in the right place.

Sorting in Python using the sorted() function

Because Python is an advanced programming language, sorting a list is very easy using in-built functions. The sorted() function sorts any list in ascending order by default. It arranges numbers numerically and strings alphabetically. And always returns a list that contains elements in a sorted manner. It does not modify any of the values stored in the original list.

Using the sorted() function, we can sort a sequence in ascending or descending order. We can also use our own custom comparator function for sorting the list instead of default functions used by the sorted() function. The syntax of the sorted() function is –

sorted(iterable list_name, key = compare_function, reverse = true_or_false);

The sorted() function has three parameters out of which the last two are optional.

  • Iterable – It contains the sequence which is to be sorted.
  • Key(optional) – A function is considered as a key or basis for sort comparison. This comparator function is defined by the user.
  • Reverse(optional) – If set true, then the sorted sequence will be in reversed order i.e. descending order. By default, it is false which means the list is sorted in ascending order.

Comparator function for custom sorting in Python

The sorted() function has an optional parameter called ‘key’ which takes a comparator function as its value and sorts the list on the basis of this key. If you want your own comparison logic for sorting a sequence, you have to use this parameter. This key function transforms each element as per the comparator function’s result before sorting. It takes the value and returns one value which is then used for sorting.

Let’s see an example of sorting the name of fruits which are basically strings. If you pass this list to the sorted() function, it will sort the strings alphabetically. But, if you want to sort on the basis of the number of vowels, consonants, etc you have to specify a custom comparator function in the ‘key’ parameter.

Comparator function to sort on the basis of the number of vowels

If you want to sort a list containing strings on the basis of the number of vowels present in the string elements, then you have to define your own custom compare function.

def vowels(fruit):
  vowels=('a', 'e', 'i', 'o', 'u')
  vowel_count=0
  for i in fruit:
    if i in vowels:
      vowel_count=vowel_count+1
  return vowel_count

The vowels() compare function acts as a key or basis for comparison. It counts the number of vowels in the strings. Then these values are arranged in order and the corresponding strings are hence sorted.

Comparator function to sort on the basis of the number of consonants

Also, you can compare a list containing strings on the basis of the number of consonants present in the elements. The comparator function which can sort on the basis of the number of consonants is –

def consonants(fruit):
        vowels=('a', 'e', 'i', 'o', 'u')
        consonant_count=0
        for i in fruit:
                if i not in vowels:
                        consonant_count=consonant_count+1
        return consonant_count

The consonants() custom compare function acts as a basis for comparison. It counts the number of consonants in the string and returns it. The sorting is done on the basis of the value returned. Then the corresponding strings are placed in that sorted order.

Program for sorting list using custom compare function in Python

Now, let’s see a Python program that sorts the list containing names of fruit on the basis of the number of vowels and consonants.

def vowels(fruit):
  vowels=('a', 'e', 'i', 'o', 'u')
  vowel_count=0
  for i in fruit:
    if i in vowels:
      vowel_count=vowel_count+1
  return vowel_count
def consonants(fruit):
        vowels=('a', 'e', 'i', 'o', 'u')
        consonant_count=0
        for i in fruit:
                if i not in vowels:
                        consonant_count=consonant_count+1
        return consonant_count
fruits=['apple','banana','cherry','grapefruit','plum','kiwi','mango']

print("ORIGINAL LIST -->")
print(fruits)
print("SORTED LIST - NUMBER OF VOWELS -->")
print(sorted(fruits,key=vowels))
print("SORTED LIST - NUMBER OF CONSONANTS -->")
print(sorted(fruits,key=consonants))

This program contains two comparator functions that act as a key for sorting on the basis of the number of vowels and consonants. The list ‘fruits’ is declared which contains names of fruits. The sorted() function is used to sort and the ‘key’ parameter is passed.

Program output

The above Python program prints the list in sorted order. Firstly, it prints the list after sorting on the basis of the number of vowels. Then, finally, it sorts on the basis of the number of consonants. The output of the program is as follows.

[email protected]:~/python$ python3 sort.py
ORIGINAL LIST -->
['apple', 'banana', 'cherry', 'grapefruit', 'plum', 'kiwi', 'mango']
SORTED LIST - NUMBER OF VOWELS -->
['cherry', 'plum', 'apple', 'kiwi', 'mango', 'banana', 'grapefruit']
SORTED LIST - NUMBER OF CONSONANTS -->
['kiwi', 'apple', 'banana', 'plum', 'mango', 'cherry', 'grapefruit']
[email protected]520-15IKBN:~/python$

Thank you for reading this tutorial and I hope it helped you.

Also read: Sort characters of a string in Python

Leave a Reply

Your email address will not be published. Required fields are marked *