Updated March 17, 2023
Introduction to Sorting in Python
Python has its own implementation of sort() function, and another is sorted() function where sort() will sort list whereas, the sorted function will return new sorted list from an iterable. The list.sort() function can be used to sort the list in ascending and descending order and takes the argument reverse, which is by default false and, if passed true, then sorts the list in descending order. Furthermore, python uses the Tim-sort algorithm to sort a list, which is a combination of merge sort and time sort.
There are 2 inbuilt functions in python to sort.
Let’s see how to sort different types of data, sort data in customize order.
- We need to perform sorting on the collection of elements or groups of elements so we will get a collection of elements in some sorting order. For sorting, the comparison needs to be performed among each element of the collection, and comparison is possible only and only if they are the same data type, so sorting we can perform on collection if they are the same data type elements, for example, integer to integer can compare but not integer to string.
- The next point is to create the collection of elements; in python, we have listed tuple, set and dictionary data structures which used to store the collection of elements. So to perform sort needs to be having a basic understanding of theses. We will use Python 3; the syntax might be slightly different if you are using Python 2 and example output as well.
Sorting Function in python
There are two inbuilt sorting functions in python.
- sort()
- sorted()
Two Sorting functions are mentioned below:
1. sort()
The sort() method sorts the elements of a given collection list in a specific order, either Ascending or Descending.
The syntax of the sort() function is:
list.sort(key = ..., reverse = ...)
- key – The parameter keyspecify function that uses for the sort comparison.
- Reverse – The parameter reverse if true, the sorted list is reversed, which means sorted in Descending order.
To get the description of the sort function, uses the help command as given below.
lis=[1,4,3,2]
help( lis.sort )
Let’s start the sort function with the example.
Example #1
Code:
l = [ 20, 50, 10, 40, 60 ]
print("list = ",l)
l.sort()
print("sorted list = ", l)
Output:
As in the above code, the unsorted list is created [ 20, 50, 10, 40, 60 ] and further apply the sort() function, which sorts the list in ascending order and does not return anything.
Next, we try the sort() function on decimal or float data type.
Example #2
Code:
l = [ 26.7, 34.23, 67.45, 89.34, 23.18 ]
print("list = ",l)
l.sort()
print("sorted list = ",l)
Output:
Next, we try the sort() function on the char data type.
Example #3
Code:
l = [ 'b', 'd', 'a', 'n', 'g']
print("liist = ", l)
l.sort()
print("sorted liist = ", l)
Output:
Next, we try the sort() function on the String data type.
Example #4
Code:
l = [ "banana", "apple", "orange", "mango" ]
print("liist = ", l)
l.sort()
print("sorted liist = ", l)
Output:
Next, we try the sort() function on different data types elements.
Example #5
Code:
l = [ 89, 56.78, "apple" ]
print("liist = ", l)
l.sort()
print("sorted liist = ", l)
Output:
Next, we try the sort() function with reverse arguments.
Example #6
Code:
l = [ 26.7, 34.23, 67.45, 89.34, 23.18 ]
print("liist = ", l)
l.sort( reverse = True )
print("sorted liist = ", l)
Output:
The unsorted list is created [ 26.7, 34.23, 67.45, 89.34, 23.18 ] and further, apply the sort() function with reverse = True, the default value of reverse is False, which sort the list in reverse order or descending order.
Next, we will try the sort() function with key arguments:
The key parameter is the most important component of the sort() function. To this argument, a function is passed, which will be used on each element in the list being sorted to arrange in the resulting order.
Let’s start the example; suppose we have a list of strings, and we want to sort a list based on the length of the strings in the list in the ascending order (shortest to longest length). The built-in len() function in python returns the length of the string, so len() can be used to pass the key argument.
Example #7
Code:
word = "Hello"
length = len(word)
print( "The length of word is ", length)
l = [ "aaa", "bbbbb", "cc", "ddd" ]
print("liist = ", l)
print( "The length of list is ", len(l))
# length of the list is 4, because it contains 4 elements
# Now we sort the list based on the length of the list elements
l.sort( key = len )
print("Sorted liist = ", l)
# Now we sort the list based on the length of the list elements and reverse
l.sort(key = len, reverse = True)
print("Sorted liist with reverse = ", l)
Output:
The resulting order of the list.sort(key = len) is a list of sort strings in order of shortest to longest. Whereas list.(key = len, reverse = True) resulting in ‘s orderthe list’s order is the longest to the shortest length. The length of each element in the list is determined by the len() function.
Next, we try the sort() function with key passing the user define the function:
Example #8
Code:
l = [ 'banana', 'orange', 'apple' ]
print("liist = ", l)
# function return second element
def sort_onSecondChar(word):
return word[1]
l.sort( key = sort_onSecondChar )
print("Sorted liist based on second character = ", l)
# Now we sort the list based on the length of the list elements and reverse
l.sort( key = sort_onSecondChar, reverse = True)
print("Sorted liist based on second character with reverse = ", l)
Output:
The resulting order of the list.sort( key = sort_onSecondChar)) is a list of sort strings in order of ascending based on the second character. Whereas a list.sort( key = sort_onSecondChar, reverse = True) resulting order of list is descending based on second character. The user determines the sorting of each element in the listfine function sort_onSecondChar ().
2. sorted()
The sorted() function call on the list or collection; it returns the new sorted list. The sorted() function does not edit or change the list on which it is called, but it returns the sorted list as a result of it.
The Syntax of sorted() function :
sorted(iterable, key, reverse)
- iterable – list, tuple, string, set, frozen set, dictionary any collection or iterable which need to sort.
- reverse- reverse specify whether the sorted list is to be reversed or not ( that is,Descending order). It is
- key– specify the function as a key to compare for the sort. It is optional.
To get the description of the sort function, uses the help command as given below.
Consider the examples:
Example #9
Code:
l = [ 2,1,3,6,5,4 ]
print("list = ", l)
sorted(l)
print( "The sorted list = ", l)
Output:
Note that we also can use the list.sort( ) function to perform the same, but the sort() function modifies the list in-place itself and returns None as the output result. Another difference of list.sort( ) function is it can apply to the only list, whereas the sorted( ) can apply to any collection or iterable.
Let’s see the example where we create the tuple (we know that to create tuple use ( and ) braces,and tuple features are it is ordered, it store duplicates, can not apply to index, and it is immutable) and apply sorted() function.
Example #10
Code:
t = ( 60, 20, 40, 10 )
print("Tuple = ", t)
re=sorted(t)
#print return of sorted()
print( "The return sorted list of sorted() = ", re)
#we check what is there in t
print( "After sorted tuple = ", t)
Output:
If the sort( ) function is applied to the tuple, it gives the “AttributeError: ‘tuple’ object has no attribute ‘sort’” error.
So sort() function cannot apply to the tuple, even cannot apply to other collections except list.
Next, we will see some examples with different data types:
Example #11
Code:
l = [ 2.89, 56.34, 45.23 ]
print("List of floating numbers = ", l)
re=sorted(l)
#print return of sorted()
print( "The return list of sorted() floating numbers = ", re)
lc = [ 'l', 'e', 'g', 'a', 'd' ]
print("List of characters = ", lc)
re=sorted(lc)
#print return of sorted()
print( "The return list of sorted() characters = ", re)
Output:
Next, we will try the sorted() function with reverse parameter:
Let us consider the example:
Example #12
Code:
l = [ 2,1,3,6,5,4 ]
print("List = ", l)
re=sorted(l, reverse=True )
#print return of sorted()
print( "The return list of sorted() with reverse = ", re)
Output:
Next, we will see the sorted() function with the key parameter; in the below code snapped the passing len() function to the key parameter, so then the sorted() function will return a list in sorting order based on the length of elements.
Example #13
Code:
l = ['aaaa', 'bb', 'ccc', 'ddddd']
print("List = ", l)
re=sorted(l, key = len )
#print return of sorted()
print( "The return list of sorted() with key = ", re)
Output:
Next, we will see a sorted() function with key parameters as the user defines the function, in below code snapped passing returnSecond () function to key parameter. The returnSecond() function is the user define the function, which just returns the second element, so the sorted() function returns a new sorted list in sorting order based on the second element of the tuple. If we want to sort on the base of the first element, then edit the returnSecond() function to return the first element as (L[0]).
Example #14
Code:
# return second element for sort
def returnSecond( L ):
return L[1]
# list of tuple
list = [ ('a', 40),('b', 30), ('c', 20), ('d', 10) ]
# sorting list with key = returnSecond (returnSecond function which return second element so sort done based on seceond elemet)
sortedList = sorted(list, key = returnSecond)
# print list
print('The sorted list:', sortedList)
Output:
We alter the above code by using the lambda function (the lambda function is an anonymous function, simulates the same as inline functions of C and C++).
Example #15
Code:
# list of tuple
list = [ ('a', 40),('b', 30), ('c', 20), ('d', 10) ]
# sorting list with key = lambda x : x[1] (lambda function which return second element so sort done based on second element)
sortedList = sorted( list, key = lambda x : x[1])
print( "The sorted list = ", sortedList)
Output:
The above code alters to sort based on the first element by altering the lambda function.
Example #16
Code:
# list of tuple
list = [ ('a', 40),('b', 30), ('c', 20), ('d', 10) ]
# sorting list with key = lambda x : x[0] (lambda function which return first element so sort done based on first element)
sortedList = sorted( list, key = lambda x : x[0])
# print list
print('The sorted list:', sortedList)
Output:
Now let’s create a list of student details and to store each student details in the tuple we will use. One tuple contains one student record, the first element in the tuple is the name of the student, the second element is the roll no of the student, and the third element is the total marks of the student. Next, we want to store the student details in order of their marks, so let us start the coding.
Example #17
Code:
students = [ ('john', 1, 60),('jane', 2, 70),('dave', '3', 70.5),('joseph', 1, 92) ]
print( "The Student List = ", students)
# sorting the student list of tuple based on the third element that is marks
sortedlist = sorted(students, key=lambda stud : stud[2])
print("The sorted list = ", sortedlist)
#reverese
sortedlist = sorted(students, key=lambda stud : stud[2], reverse=True)
print("The sorted list with reverse=True ", sortedlist)
# Display the student name and marks in sorting order of their marks
sortedlist = sorted(students, key=lambda stud : stud[2])
print("The student names and marks in order of their marks")
print("name","marks")
for x in sortedlist:
print(x[0],x[2])
Output:
Conclusion
The sort() and sorted() function use to sort the collection. The list.sort() edit to the list itself, whereas the sorted(list) not edit to the list return the new sorted list. The sort() function applies only to the list, whereas the sorted() function can apply to all collections like list, tuple, dictionary and all.
Recommended Articles
This is a guide to Sorting in Python. Here we discuss the two inbuilt sorting functions in python with the program and output. You may also look at the following article to learn more –