My approach to sorting algorithm For practicing purposes, I had the idea of making a sorting algorithm in Python.

My approach to it was to iterate through a given unsorted list to find the shortest number in it, add the number to a second list, remove shortest number from unsorted list, do that until the unsorted list is empty and return the sorted list.

How could my code be improved?

from math import inf
from random import randint

def my_sort(my_list):
    """
    Iterate through list and find shortest number, add
    shortest number to list until there are none left,
    return sorted list (shortest to highest).
    """
    unsorted_list = [*my_list]
    sorted_list = []
    for item in my_list:
        shortest_num = inf
        for num in unsorted_list:
            if num &lt; shortest_num:
                shortest_num = num
        unsorted_list.remove(shortest_num)
        sorted_list.append(shortest_num)
    return sorted_list

# Randomly generate a list of 20 numbers ranging from -20 to 20
random_list = [randint(-20, 20) for i in range(20)]

print(random_list)
print(my_sort(random_list))
Since the goal is the best possible implementation of this algorithm, I'd suggest the following. However, faster algorithms do exist.


To conform to PEP8 make sure you have two blank lines after your imports and surrounding function definitions.
Since, you aren't editing each item, but rather adding and removing items until the list is sorted, I'd use the while keyword.
The builtin min function is faster than looping through yourself. If you want to make your own minimum function as an exercise you can always do that and replace min with your own my_min say


My Code:

def my_sort2(my_list):
    unsorted_list = [*my_list]
    sorted_list = []
    while len(unsorted_list) &gt; 0:
        shortest_num = min(unsorted_list)
        sorted_list.append(shortest_num)
        unsorted_list.remove(shortest_num)
    return sorted_list


When timing mysort2 vs your mysort, I get a 12% improvement on my machine.

Timing code: (Not the nicest but it does the job)

t1 = inf
t2 = inf
for _ in range(1000):
    t1 = min(t1, timeit.timeit(
        stmt=f'my_sort(random_list)',
        setup=f'from __main__ import my_sort, random_list',
        number=100))
    t2 = min(t2, timeit.timeit(
        stmt=f'my_sort2(random_list)',
        setup=f'from __main__ import my_sort2, random_list',
        number=100))