Python Sort() method

后端 未结 4 476
感情败类
感情败类 2020-12-11 09:22

I am starting to learn Python.

Can someone explain why sort() returns None?

alist.sort()            ## correct
alist = blist.sort()    ## NO incorrec         


        
相关标签:
4条回答
  • 2020-12-11 09:34

    alist.sort() sorts alist in-place, modifying alist itself.

    If you want a new list to assign somewhere, use blist = sorted(alist)

    • list.sort(): http://docs.python.org/library/stdtypes.html#mutable-sequence-types
    • sorted(): http://docs.python.org/library/functions.html#sorted
    0 讨论(0)
  • 2020-12-11 09:34

    Use the following:

    alist = sorted(blist)
    
    0 讨论(0)
  • 2020-12-11 09:49

    When you want to perform the sorting on same list then you have to use sort() method of list. But If you dont want to change the sequence of original list but you need a sorted copy of the original list then use sorted() inbuilt function.

    0 讨论(0)
  • 2020-12-11 09:50

    Answering to his question, it returns none because the method always returns None. When you use it, it automatically modifies the list, so it does not keep the original intact (ie it does not return a sorted copy of the list).

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