Question
Both sort()
and sorted()
can be used to sort a list. What is the difference between them and when would I want to use one versus the other?
Answer
The primary difference between the list sort()
function and the sorted()
function is that the sort()
function will modify the list it is called on. The sorted()
function will create a new list containing a sorted version of the list it is given. The sorted()
function will not modify the list passed as a parameter. If you want to sort a list but still have the original unsorted version, then you would use the sorted()
function. If maintaining the original order of the list is unimportant, then you can call the sort()
function on the list.
A second important difference is that the sorted()
function will return a list so you must assign the returned data to a new variable. The sort()
function modifies the list in-place and has no return value.
The example below shows the difference in behavior between sort()
and sorted()
. After being passed to sorted()
, the vegetables
list remains unchanged. Once the sort()
function is called on it, the list is updated.
vegetables = ['squash', 'pea', 'carrot', 'potato']
new_list = sorted(vegetables)
# new_list = ['carrot', 'pea', 'potato', 'squash']
print(new_list)
# vegetables = ['squash', 'pea', 'carrot', 'potato']
print(vegetables)
vegetables.sort()
# vegetables = ['carrot', 'pea', 'potato', 'squash']
print(vegetables)