Skip to content

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

  • by

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

A simple example code sorts the given list in ascending order using a while loop. Use the 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 or suggestions on this Python sorting tutorial.

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.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading