Python sort() function
Python provides many built-in functions for solving many problems that arise in different situations in programs. One of such methods is the sort () method. In this article, the syntax and the mechanism of the sort method will be discussed, along with example programs.
Use of sort() function
This built-in method is used to sort the elements of the given list in order, either ascending or descending order.
Instead on writing a whole logic to sort the elements, we can simply use this method to get the mechanism with a smaller number of lines.
Syntax
list_name. sort (key = ____, reverse = _____)
Parameters in the syntax:
- Key: Represents the function that serves as a key for the comparison to sort the elements in the list.
- Reverse: If mentioned true, the sorted list will be reversed or it will be sorted in the descending order.
The sort () method does not return any value. It just modifies the original list, and if we want it we can print the original list.
sort () vs. sorted ()
There is another function in Python, which is sorted (), and is also used to sort the elements of a list in order but the difference between using these two functions would be:
- The sort () function as mentioned above does not return any value rather changes/ modifies the original list into the sorted list
- The sorted () function returns the sorted list and does not change a thing in the original list. This can be used when we need the sort made in a function.
Example
Let us look into it with a simple example to sort the vowels in the alphabetical order:
Vowels = [‘u’, ‘e’, ‘a’, ‘i’, ‘o’]
Vowels. sort ()
This modifies the vowels list but doesn’t return or print anything. If we need the output, we need to print it:
print (Vowels)
Now, the output will be [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]
To sort in descending order:
As discussed in the syntax, the function has an optional parameter reverse which when declared True, sorts the list in the descending order.
Example:
Vowels = [‘u’, ‘e’, ‘a’, ‘i’, ‘o’]
Vowels. sort (reverse = True)
print (Vowels)
Output:
[‘u’, ‘o’, ‘i’, ‘e’, ‘a’]
As you can see, the alphabets are sorted in the reverse order of the alphabetical order which is the descending order.
Utilizing key function
If we need to sort a list in ascending or descending order, then we can use the simple syntax but if we need some custom sorting order to follow, we can use the key parameter specified in the syntax.
Assigning the key to a sorting function enables the custom sort we want.
Example program 1:
Students = [
{'Name': 'Louis', 'age': 15, 'marks': 98},
{'Name': 'Zayn', 'age': 16, 'marks': 97},
{'Name': 'Liam', 'age': 17, 'marks': 92},
{'Name': 'Harry', 'age': 16, 'marks': 89},
]
def get_name (Students):
return Students. get ('Name')
def get_age (Students):
return Students. get ('age')
def get_marks (Students):
return Students. get ('marks')
Students. sort (key = get_name)
print (Students, end = '\n\n')
Students. sort (key = get_age)
print (Students, end = '\n\n')
Students. sort (key = get_marks, reverse = True)
print (Students, end = '\n\n')
Output:
[{'Name': 'Harry', 'age': 16, 'marks': 89}, {'Name': 'Liam', 'age': 17, 'marks': 92}, {'Name': 'Louis', 'age': 15, 'marks': 98}, {'Name': 'Zayn', 'age': 16, 'marks': 97}]
[{'Name': 'Louis', 'age': 15, 'marks': 98}, {'Name': 'Harry', 'age': 16, 'marks': 89}, {'Name': 'Zayn', 'age': 16, 'marks': 97}, {'Name': 'Liam', 'age': 17, 'marks': 92}]
[{'Name': 'Louis', 'age': 15, 'marks': 98}, {'Name': 'Zayn', 'age': 16, 'marks': 97}, {'Name': 'Liam', 'age': 17, 'marks': 92}, {'Name': 'Harry', 'age': 16, 'marks': 89}]
Explanation:
As you can see, we declared a dictionary of Students and their details name, age, and marks. Then, we used the sort () function to sort the dictionary using different parts.
In the first sort, we sorted the dictionary by means of the names of the students, in the second, age and in the third, we used marks to sort the students. You can observe the difference in the sorting order in the output of the program.
In order to get the key functions, we created our own custom functions get_name, get_age and get_marks that return the values we want to sort the keys of the dictionary. Python by default sorts the strings in alphabetical order and integers in the ascending order. To change the order to descending order, we used the reverse parameter and assigned it to True.
Example program 1:
In Python, if we sort tuples, by default the sorting will be done with respect to the first elements of the tuples. We can change it to the second element and sort the tuples, here is the example using the sort () method:
def take_second (elem):
return elem [1]
tuple_list = [(2, 2), (3, 4), (4, 1), (1, 3)]
tuple_list.sort (key=take_second)
print ("Sorted list:", tuple_list)
Output:
Sorted list: [(4, 1), (2, 2), (1, 3), (3, 4)]
Explanation:
We used a function to select the second elements in the tuples in the tuple_list and then we assigned the key of the sort () method to the function. This way, we ordered the tuples according to the ascending order of the second elements of the tuples in the list.
In the same example, if we did not specify the key to the second elements:
tuple_list = [(2, 2), (3, 4), (4, 1), (1, 3)]
tuple_list.sort()
print("Sorted list:", tuple_list)
Output:
Sorted list: [(1, 3), (2, 2), (3, 4), (4, 1)]
Explanation:
Now, we didn’t specify any custom key function. By default, the tuples are arranged in the order of the ascending order of the first elements of the tuples in the list.
Note: Find out the difference between both the outputs and then you can differentiate the difference.
Example:
num = [1, 3, 4, 2]
num.sort()
print(num)
dec_num = [2.01, 2.00, 3.67, 3.28, 1.68]
dec_num.sort()
print(dec_num)
strings = ["Tutorials", "and", "Examples"]
strings.sort()
print(strings)
Output:
[1, 2, 3, 4]
[1.68, 2.0, 2.01, 3.28, 3.67]
['Examples', 'Tutorials', 'and']
Explanation:
In this example, we sorted an integer list, a floating-point number list, and a string list. As we discussed above, the integers and floating point numbers are sorted in ascending order of the values and the strings are sorted in the alphabetical or ASCII order.