recursively sorting a list using min()

Question:

def sort(L,Lsorted):

    if len(L)==1:
        return Lsorted.append(L[0])
    a = min(L)
    Lsorted.append(a)
    L.remove(a)
    return sort(L,Lsorted)

The idea is that each time, you remove the smallest element of L and append to another list, and then in the end you return the other list.

This code returns None when I do this:

if __name__=='__main__':
    L = [9,1,11]
    L1 = []
    print(sort(L,L1))
Asked By: Alice Li

||

Answers:

.append is an in-place operation so when you return Lsorted.append(L[0]) you get back None. Try this

if len(L)==1:
    Lsorted.append(L[0])
    return Lsorted
Answered By: Kraigolas
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.