Sort List with Custom Comparator in Python (Example)
This tutorial explains how to sort a list with a custom comparator in the Python programming language. The post will contain one example of sorting a list with a custom comparator. To be more specific:
Let’s do this!
Creating Example Data and Importing Modules
In this tutorial, we’ll utilize the functools module to create a comparator as a function to sort a list. Therefore, let’s first import the module and then create a sample string list.
import functools # importing functools module str_list = ["Statistics", "Data", "Science", "Python", "String", "Hello"] # generating sample string list
Example: Sorting List Using Custom Comparator Function
First, let’s define a custom comparator function of choice. In this example, it is a function that will take two strings and return -1,0 or 1 with respect to the comparison between the second character in the strings. See the respective Python code below.
def mycmp(a, b): # defining compare function if a > b: return 1 elif a < b: return -1 else: return 0
print(sorted(str_list, key=functools.cmp_to_key(mycmp))) # sorting and printing the list # ['Data', 'Science', 'Hello', 'Statistics', 'String', 'Python']
Well done! Looks like our function mycmp() works as it is supposed to.
Video, Further Resources & Summary
If you need further explanations on the contents of this tutorial, I recommend watching the following video on my YouTube channel. I’m explaining the Python programming code of this article in the video.
The YouTube video will be added soon.
Furthermore, you might want to read some of the related tutorials at https://statisticsglobe.com/.
- Sort List of Integers in Python
- Sort List of Floats in Python
- Access List Index in for Loop in Python
- Access Multiple List Elements by Index in Python
- Python Programming Overview
Summary: This tutorial has illustrated how to create a sorted list with a custom comparator in the Python programming language. In case you have further questions, tell me about them in the comments section.
This page was created in collaboration with Ömer Ekiz. Have a look at Ömer’s author page to get more information about his professional background, a list of all his tutorials, as well as an overview of his other tasks on Statistics Globe.
Statistics Globe Newsletter