Different Ways to sort a Python List


Different Ways to sort a Python List

As the Python list is Heterogenous, i.e. it can be used to save data of various data types, python provides us with the in-built methods to sort this data. We can sort this data in different ways, like ascending order, descending order, custom sort, case-sensitive sort, case-in-sensitive sort, or reversing the order, etc. Let us go through all these methods one by one:

Different Ways to sort a Python List

Ascending Order – in-place sorting

In Python, we have the sort() method to sort the list in ascending order by default. This method can be used to sort the numbers as well as alphabets. It will perform the in-place sorting, i.e. it will modify the order of the original list.

Few Examples:

In-place Sorting.

In [1]:
namelist = ["Charlie", "David", "Adam"]
namelist.sort()
print(namelist)
['Adam', 'Charlie', 'David']

Sorting Numbers

In [2]:
markslist = [55, 80, 60, 90, 70]
markslist.sort()
print(markslist)
[55, 60, 70, 80, 90]

Ascending Order – temporary sort

As the sort() method will perform the in-place sorting, i.e. modify the original list, Python also provides with the sorted() function to perform the temporary sorting. It will not modify the original list, we have to save the content of the sorted() method in a new variable.

Original list is not modified.

In [1]:
namelist = ["Charlie", "David", "Adam"]
result = sorted(namelist)

print("Original List :", namelist)
print("Sorted List :",result)
Original List : ['Charlie', 'David', 'Adam']
Sorted List : ['Adam', 'Charlie', 'David']

Differences between sort() method and sorted() function

Here are the key differences between the sort() method and the sorted() function:

Differences between sort() method and sorted() function

Descending order – using the key

In case, the list needs to be sorted in the descending order, we simply have to pass the argument “reverse = True” to sort the items of the list in descending order. This argument works for both the sort() method and the sorted() function.

sort() method: Descending order

In [1]:
namelist = ["Charlie", "David", "Adam"]
namelist.sort(reverse = True)
print(namelist)

sort() method: Sorting numbers in descending order

In [2]:
markslist = [55, 80, 60, 90, 70]
markslist.sort(reverse = True)
print(markslist)

sorted() function

In [3]:
namelist = ["Charlie", "David", "Adam"]
final = sorted(namelist, reverse = True)
print(final)

Custom sort and Case-insensitive Sort

We can create our custom function to return the order in which items need to be sorted. This function can be called by passing the argument “key = function name” to the sort method.

Case-sensitive sort

By default, the sort() method and the sorted() functions will sort all the capital letters first and then the lower case letters, which means by default they are performing the case-sensitive sort.

Case-insensitive sort

For the case-insensitive sort, we have to make sure that all the content shares the same case, i.e. either upper or lower. Here, in this case, we will convert all text to lowercase using the in-built function str.lower () and pass this function as the key to the sort() method or the sorted() function.

Custom sort, as per the length of characters in each word.

In [1]:
def itemlength(name):
    return len(name)


namelist = ["Charlie", "David", "Adam", "Benjamin"]
namelist.sort(key = itemlength)
print(namelist)
['Adam', 'David', 'Charlie', 'Benjamin']

Case sensitive sort

In [2]:
namelist = ["Charlie", "David", "adam", "Benjamin"]
namelist.sort()
print(namelist)
['Benjamin', 'Charlie', 'David', 'adam']

Ignoring the case.

In [3]:
namelist = ["Charlie", "David", "adam", "Benjamin"]
namelist.sort(key = str.lower)
print(namelist)
['adam', 'Benjamin', 'Charlie', 'David']

Sorting a nested list

Nested list means when we have a list inside another list. For example, we have data of 5 employees in a list with columns as Name, Gender, and Experience. Let’s see how sorting will work in this case:

List of Employees

Default Sort

By default, it will sort the items based on the first column in the ascending order.

In [1]:
employees = [["Bill", "Male", 10], ["Mark", "Male", 8], ["Lisa", "Female", 8], ["Marie", "Female", 7], ["Steve", "Male", 12]]
employees.sort()
print(employees)
[['Bill', 'Male', 10], ['Lisa', 'Female', 8], ['Marie', 'Female', 7], ['Mark', 'Male', 8], ['Steve', 'Male', 12]]

Sort a Specific Column

To sort the data in a specific order, the parameter key has to be used along with the lambda function.

In the below example, we are sorting elements as per the experience.

In [1]:
employees = [["Bill", "Male", 10], ["Mark", "Male", 8], ["Lisa", "Female", 8], ["Marie", "Female", 7], ["Steve", "Male", 12]]
employees.sort(key = lambda n : n[2])
print(employees)
[['Marie', 'Female', 7], ['Mark', 'Male', 8], ['Lisa', 'Female', 8], ['Bill', 'Male', 10], ['Steve', 'Male', 12]]

Reversing order

We can reverse the items of the list using two ways

  1. The reverse() method
  2. Negative step

Using reverse method.

In [1]:
namelist = ["Charlie", "David", "Adam", "Benjamin"]
namelist.reverse()
print(namelist)
['Benjamin', 'Adam', 'David', 'Charlie']

Using negating step

In [2]:
namelist = ["Charlie", "David", "Adam", "Benjamin"]
print(namelist[::-1])
['Benjamin', 'Adam', 'David', 'Charlie']

References

  1. Sorting HOW TO
  2. 10 Ways to Sort List in Python