Why does “return list.sort()” return None, not the list?

前端 未结 7 727
感情败类
感情败类 2020-11-21 06:55

I\'ve been able to verify that the findUniqueWords does result in a sorted list. However, it does not return the list. Why?

def fin         


        
7条回答
  •  后悔当初
    2020-11-21 07:38

    To understand why it does not return the list:

    sort() doesn't return any value while the sort() method just sorts the elements of a given list in a specific order - ascending or descending without returning any value.

    So problem is with answer = newList.sort() where answer is none.

    Instead you can just do return newList.sort().

    The syntax of the sort() method is:

    list.sort(key=..., reverse=...)
    

    Alternatively, you can also use Python's in-built function sorted() for the same purpose.

    sorted(list, key=..., reverse=...)
    

    Note: The simplest difference between sort() and sorted() is: sort() doesn't return any value while, sorted() returns an iterable list.

    So in your case answer = sorted(newList).

提交回复
热议问题