Difference between list.sort() and sorted() in Python?

There are 2 way to sort the elements in the list, the built-in list method list.sort() and the built-in function sorted(). Although both will sort the elements of a list, there is a huge difference in the way they work.

Differences and similarities:

The primary difference between the two is that list.sort() will sort the original list in-place. It changes the indexes of the elements and it returns 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.

numbers = [20, 30, 10, 0, 50, 60, 40, 70]

print(sorted(numbers))

print(numbers)

print(numbers.sort())

print(numbers)

Try running the program here — Python Editor | givemefive.ai

The optional arguments — key and reverse is same for both list.sort() and sorted() and can be called on each list element prior to making comparisons.

When is the right time to use them?

list.sort() should be used whenever you are okay with changing the original list and retrieving the original order of the elements is not required. On the other hand, sorted() should be used when the object to be sorted is an iterable (e.g. list, tuple, dictionary, string) and when we require a sorted list containing all elements.

Students of age group 8–12 know these methods and have built amazing projects which can be seen here-Project Page | givemefive