Python interview Question — Diference between sort() and sorted() in Python.

Muhammad Abdullah
2 min readOct 4, 2022
Photo by Alex Chumak on Unsplash

Abstaract:

Python is a programming language that is gaining popularity because of its simplicity and readability. It is one of the most popular and widely used languages in the world. Python has a clean syntax and it has a large standard library, which makes coding easier.

In this article I will share one of the most asked Python interview question which is popular among programmers and developers.

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

Python provides two functions to sort a list, list.sort() and list.sorted(). Although both will sort the elements of a list, if used incorrectly they can produce unexpected or undesired results. The key difference between list.sort() and sorted() is

  1. sort() is a list method that sorts the items of a list in place while sorted() is a function that returns a sorted copy of the list.
  2. sorted() accepts any iterable list.list.sort() is a method of the list class and can only be used with lists.

Explaination:

The sort() function sorts the items of the list in place, i.e., it changes the order of the items in memory, but does not alter any copies of this list. sort()mutate its indexes and return None on the other way sorted()function returns a new, sorted copy of this list leaving the original list unchanged.

Similarity between list.sort() and sorted() in Python.

Both list.sort() and sorted() have the same key and reverse optional arguments and can be called on each list element prior to making comparisons.

When to use each one

list.sort() should be used whenever mutating the list is intended and retrieving the original order of the elements is not desired. On the other hand, sorted() should be used when the object to be sorted is an iterable (e.g. list, tuple, dictionary, string) and the desired outcome is a sorted list containing all elements.

--

--