Python provides two ways to sort a list, the built-in list method
list.sort() and the built-in function
sorted(). Although both will sort the elements of a list, if used incorrectly they can produce unexpected or undesired results.
The primary difference between the two is that
list.sort() will sort the list in-place, mutating its indexes and returning
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]
sorted() have the same
reverse optional arguments and can be called on each list element prior to making comparisons.
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.
Would you like to help us improve 30 seconds of code?Take a quick survey
Returns the difference between two lists, after applying the provided function to each list element of both.
Returns the symmetric difference between two lists, after applying the provided function to each list element of both.
Calculates the difference between two iterables, without filtering duplicate values.