What is the difference between `sorted(list)` vs `list.sort()`?

后端 未结 6 2219
温柔的废话
温柔的废话 2020-11-22 09:19

list.sort() sorts the list and replaces the original list, whereas sorted(list) returns a sorted copy of the list, without changing the original li

6条回答
  •  鱼传尺愫
    2020-11-22 09:54

    The main difference is that sorted(some_list) returns a new list:

    a = [3, 2, 1]
    print sorted(a) # new list
    print a         # is not modified
    

    and some_list.sort(), sorts the list in place:

    a = [3, 2, 1]
    print a.sort() # in place
    print a         # it's modified
    

    Note that since a.sort() doesn't return anything, print a.sort() will print None.


    Can a list original positions be retrieved after list.sort()?

    No, because it modifies the original list.

提交回复
热议问题