Search code examples
python-3.xsortingreturn

Sorting a list with python


I have 2 parameters, one is a list and the other is a string. There are 3 specific strings to use "asc", "desc", "none". I wrote a function to sort a list depending on any of the string but it is returning none no matter what i put

This is what i tried below:

def sort_a_list(num_list, a_string):
    #The string should either be "asc", "desc", "none" and it should do any of this according to what is chosen
    if a_string == "asc":
        return num_list.sort()
    elif a_string == "desc":
        return num_list.sort(reverse=True)
    else:
        return num_list
    
result = sort_a_list([10,2,5,6,25,14], "asc")
print(result)

Solution

  • In Python, l.sort() is an in-place operator, which means that when you call it, it sorts the list in place (no new list created) and then returns nothing or None.

    To remedy your issue, you could either:

    1. Use l.sort(), but then return the list on the next line like so:
    def sort_a_list(num_list, a_string): #The string should either be "asc", "desc", "none"
        if a_string == "asc":
            num_list.sort() 
        elif a_string == "desc": 
            num_list.sort(reverse=True) 
        return num_list
    
    1. Use sorted(l). This method sorts a new copy of the string and returns this sorted copy. For example:
    def sort_a_list(num_list, a_string): #The string should either be "asc", "desc", "none"
        if a_string == "asc":
            return sorted(num_list)
        elif a_string == "desc": 
            return sorted(num_list, reverse=True) 
        return num_list