Skip to content

How to sort a list in Python without sort function | Example code

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:

How to sort a list in Python without sort function

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.

3 thoughts on “How to sort a list in Python without sort function | Example code”

Leave a Reply

Your email address will not be published. Required fields are marked *