Python

Python Sort Function

Python is a widely-used general-purpose programming language. The key reasons for Python’s popularity are its simple syntax, built-in modules, and functions that allow you to perform powerful tasks. The sort() function is a built-in function in Python that sorts the elements in a list, in ascending order by default. You can also use the sort() function to sort the elements in descending order or define the sorting criteria. In this article, the sort() function is explained in detail with some simple examples.

Syntax of the sort() Function

The syntax of the sort() function is as follows:

list_obj.sort(reverse= “”,key= “”)

Both parameters inside the sort() function are optional. The reverse parameter is used to sort the list in descending order. If “reverse=true,” then the list will be sorted in descending order; otherwise, “reverse=false” by default. The “key” parameter specifies the function that defines the sorting criteria. The sort() function does not change the order of elements in the original list object; rather, it creates a copy of the list object with sorted elements and returns it as the output.

Examples of sort() Function

The following examples cover the usage of the sort() function in greater detail.

Example 1: Sorting a List of Strings

The sort() function sorts lists of strings, integers, and floating-point numbers. In this first example, we will sort the following list of strings in ascending order using the sort() function.

#declaring a list of students

student = ['Mark','John','Taylor','Donald','Joseph','Albert','Cameron']

print("The original list is: ")

print(student)

#sorting the list

#using the sort() function

student.sort()

print("The sorted list is: ")

print(student)

Output

As you can see, the list has been sorted successfully.

Next, we will sort the list of string elements in descending order. In this case, the reverse value is equal to “true.”

#declaring a list of students

student = ['Mark','John','Taylor','Donald','Joseph','Albert','Cameron']

print("The original list is: ")

print(student)

#sorting the list

#using the sort() function with the reverse parameter

student.sort(reverse=True)

print("The sorted list is: ")

print(student)

Output

In this example, we will sort the list of vowel alphabets in ascending and descending order, respectively.

#declaring a list of students

my_list = ['i','u','a','o','e']

print("The original list is: ")

print(my_list)

#sorting the list in ascending order

#using the sort() function

my_list.sort()

print("The sorted list in ascending order: ")

print(my_list)

#sorting the list in descending order

my_list.sort(reverse=True)

print("The sorted list in descending order: ")

print(my_list)

Output

Now, we will sort the list based on the length of each element. The funclen() function checks the list of each item and returns it. The sort() function then sorts the elements in the list based on the length of each element, with the elements with the shortest length coming first in the sorted list.

#declaring a function

def funcLen(ele):

    return len(ele)

#declaring a list of animals

my_list = ['Goat','Cat','Elephant','Crocodil','Rabbit','Rhinoceros']

print("The original list is: ")

print(my_list)

#sorting the list using the funcLen function

my_list.sort(key=funcLen)

print("The sorted list is: ")

print(my_list)

Output

To sort the elements so that the higher-length items come first, the reverse parameter value must be “true.”

#declaring a function

def funcLen(ele):

    return len(ele)

#declaring a list of animals

my_list = ['Goat','Cat','Elephant','Crocodil','Rabbit','Rhinoceros']

print("The original list is: ")

print(my_list)

#sorting a list using the funcLen function

my_list.sort(reverse=True,key=funcLen)

print("The sorted list is: ")

print(my_list)

Output

Example 2: Sorting a List of Integers

The sort() function can also sort a list of integers in ascending or descending order.

In the following example, we will declare a list of integers and sort it in both ascending and descending order.

#declaring a list of integers

numList = [10,9,2,3,1,4,5,8,7]

#printing the original list

print("The original list is: ")

print(numList)

#sorting the list in ascending order

numList.sort()

#printing the ascending order sorted list

print("The sorted list in ascending order: ")

print(numList)

#sorting the list in ascending order

numList.sort(reverse=True)

#printing the descending order sorted list

print("The sorted list in descending order: ")

print(numList)

Output

The integer numbers list has now been sorted in ascending and descending order.

Example 3: Sorting a List of Floating-Point Numbers

The sort() function is also applicable to a list of floating-point numbers.

In the following example, we will sort a list of floating-point numbers in both ascending and descending order.

#declaring a list of integers

numList = [1.5,1.2,4.5,10.6,11.5,3.3,3.83,3.85]

#printing the original list

print("The original list is: ")

print(numList)

#sorting the list in ascending order

numList.sort()

#printing the ascending order sorted list

print("The sorted list in ascending order: ")

print(numList)

#sorting the list in ascending order

numList.sort(reverse=True)

#printing the descending order sorted list

print("The sorted list in descending order: ")

print(numList)

Output

The floating-point numbers list has now been sorted in ascending and descending order.

Example 4: Sorting a List of Dictionary Items

A dictionary can be placed inside a list as an element.

In the following example, we will sort dictionary elements in a list while creating a dictionary of students. We will sort the elements based on their age values.

# A function that returns the 'year' value:

def ageFunc(ele):

  return ele['age']

#declaring a list of student dictionaries

students = [

  {'name': 'Mark', 'email':'[email protected]' ,'age': 28},

  {'name': 'John', 'email':'[email protected]' ,'age': 23},

  {'name': 'Albert', 'email':'[email protected]' ,'age': 21},

  {'name': 'Cameron', 'email':'[email protected]' ,'age': 27},

  {'name': 'Taylor', 'email':'[email protected]' ,'age': 25}

]        

#sorting the list

students.sort(key=ageFunc)

#printing the sorted list

print(students)

Output

Conclusion

The sort() function is a built-in function in Python that sorts a list of elements. The sort() function can take two optional parameters, i.e., reverse and key. This article explained how to use the Python sort() function in detail with various examples.

About the author

Kamran Sattar Awaisi

Kamran Sattar Awaisi

I am a software engineer and a research scholar. I like to write article and make tutorial on various IT topics including Python, Cloud Computing, Fog Computing and Deep Learning. I love to use Linux based operating systems.