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

前端 未结 7 709
感情败类
感情败类 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:33

    Python has two kinds of sorts: a sort method (or "member function") and a sort function. The sort method operates on the contents of the object named -- think of it as an action that the object is taking to re-order itself. The sort function is an operation over the data represented by an object and returns a new object with the same contents in a sorted order.

    Given a list of integers named l the list itself will be reordered if we call l.sort():

    >>> l = [1, 5, 2341, 467, 213, 123]
    >>> l.sort()
    >>> l
    [1, 5, 123, 213, 467, 2341]
    

    This method has no return value. But what if we try to assign the result of l.sort()?

    >>> l = [1, 5, 2341, 467, 213, 123]
    >>> r = l.sort()
    >>> print(r)
    None
    

    r now equals actually nothing. This is one of those weird, somewhat annoying details that a programmer is likely to forget about after a period of absence from Python (which is why I am writing this, so I don't forget again).

    The function sorted(), on the other hand, will not do anything to the contents of l, but will return a new, sorted list with the same contents as l:

    >>> l = [1, 5, 2341, 467, 213, 123]
    >>> r = sorted(l)
    >>> l
    [1, 5, 2341, 467, 213, 123]
    >>> r
    [1, 5, 123, 213, 467, 2341]
    

    Be aware that the returned value is not a deep copy, so be cautious about side-effecty operations over elements contained within the list as usual:

    >>> spam = [8, 2, 4, 7]
    >>> eggs = [3, 1, 4, 5]
    >>> l = [spam, eggs]
    >>> r = sorted(l)
    >>> l
    [[8, 2, 4, 7], [3, 1, 4, 5]]
    >>> r
    [[3, 1, 4, 5], [8, 2, 4, 7]]
    >>> spam.sort()
    >>> eggs.sort()
    >>> l
    [[2, 4, 7, 8], [1, 3, 4, 5]]
    >>> r
    [[1, 3, 4, 5], [2, 4, 7, 8]]
    

提交回复
热议问题