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

前端 未结 7 708
感情败类
感情败类 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).

    0 讨论(0)
提交回复
热议问题