Python has two kinds of sorting: a sorting method (or "member function") and a sorting function. The sort method works on the contents of an object with a name - consider it as the action that the object takes to reorder. A sort function is an operation on the data represented by an object, and returns a new object with the same contents in 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 actually means nothing. This is one of those strange, somewhat annoying details that a programmer is likely to forget after a period of absence in Python (that’s why I write this, so I don’t forget again).
The sorted() function, on the other hand, will do nothing with 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]
Remember that the return value is not a deep copy , so be careful with side effects on the items contained in 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]]