Python sort() Method: How to perform Python List Sorting

Python Sort List Thumbnail

Python’s list sort() method is used to sort a list in either ascending or descending order, additionally, you can also define the criteria to sort. 

This tutorial will provide a complete guide to all types of list sorting in Python using the sort() method.

Overview of List Sorting 

Sorting is a technique to rearrange items. Arranging the elements of a list in a certain order, such as accessing or descending based on given criteria, is referred to as sorting.

A real-life example is the student records which it is required to arrange in ascending order by name.

Imagine, a school containing hundreds of records of students in a python list, and new students are continually being added, it can be difficult to maintain the order. In situations like this, sorting can be used to organize the list by arranging the records in ascending order based on the name criteria.

A list can directly sort using the sort() method. We have a separate article on Python List if you want to read it.

sort() Method

This method takes two arguments, the first is reverse , and the second is a key.

The reverse accepts a boolean value(i.e. True or False) that decides whether to sort a list in ascending or descending order, to sort in descending order the value should be True and for ascending the value should be False. By default value is False, if you want to sort a list in ascending order you don’t have to pass this argument, as it is the default.

The key accepts a function that decides the sort criteria such as on the based of a particular field, on the bases of the length of objects, etc.

Syntax:

list_name.sort(reverse=True|False, key=function)

where,

  • list_name is the name of the list you want to sort,
  • reverse can be true or false,
  • function can be any function to decide the sort criteria

Note: The sort() method does not return a new list, it sorts the actual list, so if you use a sort method, you no longer have the access to the actual list order.

Techniques to Sort a List in Python

Here are a few norms for using the sort() method to sort a list:

  • Sort the List in Ascending Order
  • Sort the List in Descending Order
  • Sort the List using a Key
  • Sort the List using User-defined Order
  • Sort the List of Objects

Let’s examine each of them separately

1. Sort the List Elements in Ascending Order

Ascending refers to arranging the lowest value on the left side and increasing toward the highest value on the right side.

To sort a list in ascending order, the value passes to the reverse parameter should be False, since the default value is also False we don’t have to pass any parameter.

Example:

Here we created a list containing floating point numbers, then used the sort method without passing any additional parameter, and printed the list.

input = [1.2, 221, 0.025, 0.124, 1.2]

print(f'Before: {input}')

input.sort()

print(f'After: {input}')

Output:

Before : [1.2, 221, 0.025, 0.124, 1.2]
After : [0.025, 0.124, 1.2, 1.2, 221]

In the above output, you can see that the list values are sorted in ascending order.

2. Sort the List Elements in Descending Order

Descending refers to arranging the highest value on the left side and decreasing toward the lowest value on the right side.

To sort a list in descending order, the value passed to the reverse parameter should be True.

Syntax:

list_name.sort(reverse=True)

Example:

Here we created a list containing numbers, then used the sort method, passed an additional parameter “reverse=True” to sort the list in descending order, and printed the list.

input = [8, 1, 12, 0]

input.sort(reverse = True)

print(input)

Output:

[12, 8, 1, 0]

In the above output, you can see that the list values are sorted in descending order.

3. Sort the List using a Key Function

A list can sort on the bases of some predefined order. It is required to create a function that defines the criteria, and then pass the name of that function to the key parameter inside the sort() method.  

Let’s see an example for more clearance.

Example:

Here we have defined a function that returns the third element of the values of the list, this function has then passed as a key to the sort() method to sort based on the third element of the values.

# takes third element for sort
def third_element(x):
    return x[2]


input = [(2, 2, 1), (3, 4, 9), (4, 1, 0), (1, 3, 7)]

# sort list with key
input.sort(key=third_element)

# prints sorted list
print('Sorted list:', input)

Output:

Sorted list: [(4, 1, 0), (2, 2, 1), (1, 3, 7), (3, 4, 9)]

The above output shows that the list values are sorted in ascending order of their third element.

4. Sort the List using User-defined Order

Again, we can use the key parameter to pass a function to define our own sort order.

Example:

# takes third element for sort
def third_element(x):
    return x[2]


input = [(2, 2, 1), (3, 4, 9), (4, 1, 0), (1, 3, 7)]

# sorts list with key in ascending order
input.sort(key=third_element)

# prints sorted list
print('Sorted list in ascending order:', input)

# sorts list with key in descending order
input.sort(key=third_element, reverse=True)

print('Sorted list in descending order:', input)

Output:

Sorted list in ascending order: [(4, 1, 0), (2, 2, 1), (1, 3, 7), (3, 4, 9)]
Sorted list in descending order: [(3, 4, 9), (1, 3, 7), (2, 2, 1), (4, 1, 0)]

The above output shows that the list values are sorted in ascending and descending order of their third element.

5. Sort the List of Class Objects

In order to sort the list of custom objects using the sort() function, you need to define the key function specifying the object’s field, based on which you want to sort the list elements.

Example:

class Details:

    def __init__(self, name, num):
        self.name = name
        self.num = num


    def __str__(self):
        return f'Details[{self.name}:{self.num}]'


    __repr__ = __str__


D1 = Details('Safa', 12)
D2 = Details('Aman', 1)
D3 = Details('Shalini', 45)
D4 = Details('Ruh', 30)

input_list = [D1, D2, D3, D4]

print(f'Before Sorting: {input_list}')



def sort_by_num(details):
    return details.num


input_list.sort(key=sort_by_num)
print(f'After Sorting By Number: {input_list}')

In the above code example, we have created a class, and from that class, we have created multiple objects and passed them inside a list, and printed that list, you can see that the list printed has all the objects.

In order to sort its object we then defined a function, notice how we defined the return value to be a specific object’s field(num), which will be the criteria for sort. After passing the function to the sort method, we again printed the list. 

Output:

Before Sorting: [Details[Safa:12], Details[Aman:1], Details[Shalini:45], Details[Ruh:30]]
After Sorting By Number: [Details[Aman:1], Details[Safa:12], Details[Ruh:30], Details[Shalini:45]]

You can see that the list object is sorted in ascending order to their num field. Hence the output is justified.

Conclusion

In this tutorial, we have explained the sort() method which is used to sort a list in python. This method takes two arguments, the first one is “reverse” which contains a boolean value that defines the sort order, where False represents ascending order and True represents descending order. The second argument is a “key” which contains a function that defines the criteria to sort, such as based on some field, length, etc.

We have also covered the different approaches to this method to sort, such as in ascending order, descending order, on the basis of custom or user-defined criteria, etc. We also discussed the process to sort a list of class objects. Hope this tutorial helps you to sort the list in python.

References

Sorting documentation