How to sort Numbers in Python without sort function | Example Code

You can use loops statement with if statement to get sort Numbers in Python without sort function. However, you can do it with your own logic using basic code.

How to sort Numbers in Python without sort function examples

Simple example code sorts the given list in ascending order using a while loop. Using append method and remove method to update the list.

my_list = [4, 2, 3, -1, -2, 0, 1]
new_list = []

while my_list:
    min = my_list[0]
    for x in my_list:
        if x < min:
            min = x
    new_list.append(min)
    my_list.remove(min)

print(new_list)

Output:

How to sort Numbers in Python without sort function

Another example with for-loop and range function

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: [-2, -1, 0, 1, 2, 3, 4]

Do comment if you have any doubts and suggestions on this Python sorting tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.