DEV Community

Cover image for Custom sorting in Python
Zeeshan Asgar
Zeeshan Asgar

Posted on

Custom sorting in Python

Consider the following list:

employees = ['Bill Gates', 'Mark Zukerberg', 'Jeff Bezos', 'Elon Musk', 'Larry Page']
Enter fullscreen mode Exit fullscreen mode

To sort the list employees

employees.sort()
Enter fullscreen mode Exit fullscreen mode

Output

['Bill Gates', 'Elon Musk', 'Jeff Bezos', 'Larry Page', 'Mark Zukerberg']
Enter fullscreen mode Exit fullscreen mode

As we can see here the normal sorting sort the elements by alphabets. Let's say we want to sort the list by the length of each string element in the list. We can easily do that using the key parameter of the sort method.

To sort the original list employees by the length of elements

employees.sort(key=len)
print(employees)
Enter fullscreen mode Exit fullscreen mode

Output

['Elon Musk', 'Bill Gates', 'Jeff Bezos', 'Larry Page', 'Mark Zukerberg']
Enter fullscreen mode Exit fullscreen mode

In the example above we are passing a built-in len() method to sort the list by the length of elements. We can also supply our custom sort function as well instead of a built-in function.
This key function takes each element of the list, transforms it and return one value which is then used to sort the list.

sort()

sorts a list in-place in ascending or descending order. sort() method takes two parameters which are both optional:

  1. key: function which serves as the basis for comparison.
  2. reverse: if True, then it will sort the list in descending order, otherwise in ascending order. Defaults to False.

Syntax

list.sort(key=..., reverse=...)
Enter fullscreen mode Exit fullscreen mode

Let's look at another example of sorting a list of tuples using the second element:

cart =[('Mango', 5), ('Grapes', 10), ('Banana', 3), ('Melon', 5), ('Strawberry', 7)]
Enter fullscreen mode Exit fullscreen mode

To sort the cart list using the second element of each tuple

cart.sort(key=lambda x : x[1])
print(cart)
Enter fullscreen mode Exit fullscreen mode

Output

[('Banana', 3), ('Mango', 5), ('Melon', 5), ('Strawberry', 7), ('Grapes', 10)]
Enter fullscreen mode Exit fullscreen mode

There is one more method that is used to sort the iterable called sorted().

sorted()

returns a sorted list of elements in ascending or descending order.

It takes 3 parameters:

  1. iterable: Either a sequence of elements like list, string or tuple or a collection like dict, set etc.
  2. key (optional): function which serves as the basis for comparison.
  3. reverse (optional): if True, then it will sort the iterable in descending order, otherwise in ascending order. Defaults to False.

Syntax

sorted(iterable, key=..., reverse=...)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)