Search code examples
pythonpython-3.xindexingindex-error

How to change a range value in a for loop


I am getting an index error from trying to access values from a list after removing values whilst inside of a for loop. How do I change the range value in the for loop after each iteration? The function itself is to taken a list as an input and reverse the list in a new list but only by removing elements from one list into another so that the input list ends up empty.

def minsort(lst):
    new_lst = list()
    counter = 0
    while len(lst) > counter:
        smallest = lst[0]
        for i in range(1, len(lst)):
            if smallest > lst[i]:
                smallest = lst[i]
                new_lst.append(smallest)
                lst.remove(smallest)
                smallest = lst[0]
            else:
                new_lst.append(smallest)
                lst.remove(smallest)
    return new_lst

lst = [3,1,2]
print(minsort(lst))

Error that I am getting:

    if smallest > lst[i]:
IndexError: list index out of range

Edit: I am doing this without any inbuilt functions such as sorted()


Solution

  • If you're trying to sort a list in ascending order you could use:

    new_lst = sorted(lst)
    

    EDIT*

    well, this seem to work without any built-in functions:

    def minsort(lst):
        new_lst = []
    
        while lst:
            smallest = None
            for item in lst:
                if smallest == None:
                    smallest = item
                elif item < smallest:
                    smallest = item
            new_lst.append(smallest)
            lst.remove(smallest)
        return new_lst