You can use Nested for loop with if statement to get the sort a list in Python without sort function. This is not the only way to do it, you can use your own logic to get it done.
How to sort a list in Python without sort function example
Simple example code will sort all negative or positive values from a list. It will sort the list in ascending order.
my_list = [4, 2, 3, -1, -2, 0, 1]
for i in range(len(my_list)):
for j in range(i + 1, len(my_list)):
if my_list[i] > my_list[j]:
my_list[i], my_list[j] = my_list[j], my_list[i]
print(my_list)
Output:
Another Example
Taking a list from the user and then sort it.
n = int(input("List length = "))
list1 = []
for i in range(n):
x = int(input("Elements (0 a 9) = "))
if (i == 0) or (x > list1[- 1]):
list1.append(x)
else:
pos = 0
while pos < len(list1):
if x <= list1[pos]:
list1.insert(pos, x)
break
pos = pos + 1
print(list1)
Output:
List length = 4
Elements (0 a 9) = 5
Elements (0 a 9) = 2
Elements (0 a 9) = 3
Elements (0 a 9) = 1
[1, 2, 3, 5]
Do comment if you have any doubts and suggestions on this Python sort code.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Hi,
Wanted to ask how will you sort without using the range function as well the append method?
a = [3, 1, 5, 2, 4]
for i in a[1:]:
j = a.index(i)
while j > 0 and a[j-1] > a[j]:
a[j], a[j-1] = a[j-1], a[j]
j = j - 1
actually append method time complexity if O(1) so i wonder why you dont want to use that