Introduction to Sorting in Python
Python includes its own version of the sort() method, as well as another function called sorted(). Whereas the sort() function sorts a list, the sorted function returns a new sorted list from an iterable. The list.sort() method may be used to sort the list in ascending or descending order. It accepts the parameter reverse, which is set to false by default and, if supplied true, sorts the list in descending order. If the argument is omitted, the list is sorted in ascending order. In addition, the process of sorting a list in Python is handled by the Tim-sort algorithm, which is a hybrid of the merge sort and the time sort.
Python comes with two built-in functions that may be used to sort data.
Let’s look at how to sort various kinds of data, as well as how to sort data in customizing.
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 different sorting functions that are embedded right into
python.
- sort()
- sorted()
There are two sorting functions that are discussed.
below:
1. sort()
The sort() function takes a collection list as input and returns the contents arranged in the specified order, which may be either ascending or descending.
The basic building blocks 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.
Use the help command in the manner shown above to get information on the sort function.
below.
lis=[1,4,3,2]
help( lis.sort )
Now, let’s look at an example of using the sort function. Example #1 Code:
l = [ 20, 50, 10, 40, 60 ]
Output:
print("list = ",l)
l.sort()
print("sorted list = ", l)
Using the same pattern as the code before, the unsorted list [20, 50, 10, 40, 60] is generated, and then the sort() function is used. This function sorts the list in descending order and does not return any value.
After that, we apply the sort() method to the decimal or float data type and see what happens. Example #2 Code:
l = [ 26.7, 34.23, 67.45, 89.34, 23.18 ]
Output:
print("list = ",l)
l.sort()
print("sorted list = ",l)
Next, we apply the sort() method to the char data type and see what the results are. Example #3 Code:
l = [ 'b', 'd', 'a', 'n', 'g']
Output:
print("liist = ", l)
l.sort()
print("sorted liist = ", l)
The sort() method will be applied to the String data type in the next step. Example #4 Code:
l = [ "banana", "apple", "orange", "mango" ]
Output:
print("liist = ", l)
l.sort()
print("sorted liist = ", l)
The next step involves using the sort() method on a variety of data kinds’ parts. Example #5 Code:
l = [ 89, 56.78, "apple" ]
Output:
print("liist = ", l)
l.sort()
print("sorted liist = ", l)
The next step involves calling the sort() method with the opposite order of parameters. Example #6 Code:
l = [ 26.7, 34.23, 67.45, 89.34, 23.18 ]
Output:
print("liist = ", l)
l.sort( reverse = True )
print("sorted liist = ", l)
After creating the unsorted list with the coordinates [26.7, 34.23, 67.45, 89.34, 23.18], use the sort() method with the reverse parameter set to True. The reverse parameter’s default value is False. This causes the list to be sorted in reverse order, often known as descending order.
After that, we will experiment with the sort() method with the following key arguments:
The sort() function’s key argument is the most crucial part of the function’s structure. To this parameter, a function is supplied, and that function will be applied on each item in the list that is being sorted in order to arrange the items in the order that will be produced by the sorting.
Let’s begin with an example; imagine we have a list of strings, and we want to sort the list based on the ascending order of the lengths of the strings included in the list (shortest to longest length). As len(), a built-in function in Python that returns the length of the string, can be used to supply the key parameter, len() is an excellent choice. Example #7 Code:
word = "Hello"
Output:
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)
The order that is produced by list.sort(key = len) is a list of strings that are arranged from shortest to longest in terms of their length. Unlike list. (key = len, reverse = True), which results in the list’s order, which is the shortest length to the longest length, the order of the list is the longest length to the shortest length. The len() function calculates each element’s total length in the list based on its length parameter.
Next, we give the sort() method a shot while giving the key that the user has defined for the function. Example #8 Code:
l = [ 'banana', 'orange', 'apple' ]
Output:
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)
0
The list of sorted strings that was produced as a consequence of using list.sort(key = sort onSecondChar) is presented below in ascending order. This order is determined by the string’s second character. In contrast, the order of the list that is produced by a list.sort(key = sort onSecondChar, reverse = True) is reversed and is determined by the second character. Inside the listfine function known as sort onSecondChar, the ordering of each constituent is decided by the user.
().
2. sorted()
Using the sorted() method on the list or collection will result in the newly sorted list being returned. The list that the sorted() function is run on is not altered in any way, but it does return a list that has been sorted as a consequence of the method’s execution.
a syntax example for the sorted() method
:
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
.
Use the help command in the manner shown above to get information on the sort function.
below.
1
Have a look at these two examples: Example #9 Code:
l = [ 2,1,3,6,5,4 ]
Output:
print("list = ", l)
sorted(l)
print( "The sorted list = ", l)
2
It is important to keep in mind that we may also do the same thing by using the list.sort() method; however, the sort() function adjusts the list in-place and then returns None as the output result. Another distinction between the functions sorted() and list.sort() is that the former can only be applied to lists, but the latter may be used with any collection or iterable.
Let’s look at an example in which we create a tuple and then use the sorted() function on it. We already know how to create tuples by using the and braces, and we know that tuples have the following features: they are ordered, they can store duplicates, they cannot be applied to an index, and they are immutable. Example #10 Code:
t = ( 60, 20, 40, 10 )
Output:
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)
3
When the sort() method is used on a tuple, an error message that reads “AttributeError: ‘tuple’ object has no attribute’sort'” is generated.
Hence, the sort() method cannot be used to the tuple, and it also cannot be applied to any other collections outside the list.
In the next section, we will look at numerous examples using various forms of data. Example #11 Code:
l = [ 2.89, 56.34, 45.23 ]
Output:
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)
4
The following is an example of using the sorted() function using the reverse parameter:
Let us have a look at the following example: Example #12 Code:
l = [ 2,1,3,6,5,4 ]
Output:
print("List = ", l)
re=sorted(l, reverse=True )
#print return of sorted()
print( "The return list of sorted() with reverse = ", re)
5
Next, we will look at the sorted() function with the key parameter; in the code below, the passing of the len() function to the key argument was snapped, and as a result, the sorted() function will produce a list that is sorted according to the length of the components in the list. Example #13 Code:
l = ['aaaa', 'bb', 'ccc', 'ddddd']
Output:
print("List = ", l)
re=sorted(l, key = len )
#print return of sorted()
print( "The return list of sorted() with key = ", re)
6
After that, we will look at a sorted() function that takes key arguments as the user specifies the function; for example, the code below passes the returnSecond () function to the key parameter. The user defines the function known as returnSecond(), which simply returns the second element of the tuple. As a result, the sorted() function provides a new sorted list that is arranged in sorting order according to the second member of the tuple. Changing the return value of the returnSecond() method so that it returns the first element as the result of the sorting based on the first element is necessary if we want to do it (L[0]). Example #14 Code:
# return second element for sort
Output:
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)
7
The above piece of code is modified by using the lambda function. The lambda function is an anonymous function that mimics the behavior of inline functions in C and C++. Example #15 Code:
# list of tuple
Output:
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)
8
By making a change to the lambda function, the preceding code is modified to sort the items depending on the first element. Example #16 Code:
# list of tuple
Output:
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)
9
Now that we have a list of students to work with, let’s establish a tuple where we can store each individual student’s information. One student record is included in one tuple, and the first element of the tuple is the student’s name. The second element is the student’s roll number, and the third element is the student’s overall score. The next step is to save information on the students in descending order of their grades, so let’s get started with the code. Example #17 Code:
students = [ ('john', 1, 60),('jane', 2, 70),('dave', '3', 70.5),('joseph', 1, 92) ]
Output:
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])