Python Lists are a type of data structure that is mutable in nature. This means that we can modify the elements in the list. We can sort a list in Python using the inbuilt list sort() function. But in this article, we will learn how we can sort a list in a particular order without using the list sort() method.
Sort a List Without Using Sort Function in Python
Sorting is nothing but arranging the elements of a list in a particular order and this order can be either increasing or decreasing in nature. We can sort a list in Python without using the list sort() function by using nested for loops. Let us see a few examples, of how we can sort a list without the sort() function.
Sort a List in Ascending Order Without using an Extra Variable
In this example, we will have a list and we will sort it in ascending order using just the nested loop. We will compare each element in the list one by one and swap it.
Python3
#Python program to print a list # without using the sort() function # without an extra variable l1 = [ 76 , 23 , 45 , 12 , 54 , 9 ] print ( "Original List:" , l1) # sorting list using nested loops for i in range ( 0 , len (l1)): for j in range (i + 1 , len (l1)): if l1[i] > = l1[j]: l1[i], l1[j] = l1[j],l1[i] # sorted list print ( "Sorted List" , l1) |
Output:
Original List: [76, 23, 45, 12, 54, 9]
Sorted List [9, 12, 23, 45, 54, 76]
Sort a List in Ascending Order by Using an extra variable
In this example, we will have a list and we will sort it in ascending order by using the nested for loop and a temporary variable.
Python3
#Python program to print a list # without using the sort() function # using an extra variable l1 = [ 76 , 23 , 45 , 12 , 54 , 9 ] print ( "Original List:" , l1) # sorting list using nested loops for i in range ( 0 , len (l1)): for j in range (i + 1 , len (l1)): if l1[i] > = l1[j]: # temporary variable temp = l1[i] l1[i] = l1[j] l1[j] = temp # sorted list print ( "Sorted List" , l1) |
Output:
Original List: [76, 23, 45, 12, 54, 9]
Sorted List [9, 12, 23, 45, 54, 76]
Sort a List in Descending Order
In this example, instead of a predefined list, we will take a list whose values are provided by the user. Then we will sort the list in descending order without using an extra variable.
Python3
# create an empty list l1 = [] n = int ( input ( "enter number of elements required: " )) # creating a list using loop for i in range ( 0 , n): element = int ( input ()) # appending elements to the list l1.append(element) print ( "Original List:" , l1) # sorting in decending for i in range ( 0 , len (l1)): for j in range (i + 1 , len (l1)): if l1[i] < = l1[j]: l1[i], l1[j] = l1[j], l1[i] # sorted list print ( "Sorted List" , l1) |
Output:
enter number of elements required: 6
76
23
45
12
54
9
Original List: [76, 23, 45, 12, 54, 9]
Sorted List [76, 54, 45, 23, 12, 9]