sort vs sorted

发布时间 2023-05-09 11:16:36作者: xiaoxuxli

The primary difference between the two is that list.sort() will sort the list in-place, mutating its indexes and returning None, whereas sorted() will return a new sorted list leaving the original list unchanged. Another difference is that sorted() accepts any iterable while list.sort() is a method of the list class and can only be used with lists.

nums = [2, 3, 1, 5, 6, 4, 0]

print(sorted(nums))   # [0, 1, 2, 3, 4, 5, 6]
print(nums)           # [2, 3, 1, 5, 6, 4, 0]

print(nums.sort())    # None
print(nums)           # [0, 1, 2, 3, 4, 5, 6]

参考:
[1] https://www.30secondsofcode.org/articles/s/python-sortedlist-vs-list-sort/