What is the difference between sort() and sorted()?

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)
20 Likes

do we have a ‘reverse’ option in the 'sorted()' function?

6 Likes

sounds like something you can find in the documentation:

https://docs.python.org/3/howto/sorting.html#ascending-and-descending

11 Likes

Thank you. I found: it’s possible via optional agrument: reverse = True.

11 Likes

Also list.sort can only be used on lists.
sorted() can be used on any iterable (string, dictionary, etc)

18 Likes

Is there a technical term for the distinction between .sort() and sorted()? I’m wondering specifically if there’s some adjective that advanced programmers use to label the one or the other. A brief foray online reveals that Pascal commonly calls methods of the first type ‘procedure’ and the second type ‘function.’ Does Python have a similar terminological distinction? (Total noob here, btw).

2 Likes

.sort() is a method that only list objects inherit from their parent class. sorted() is a function for sorting any interable, including list. The former mutates its context list in-place and returns None, while the latter returns a copy of the argument object, sorted. Both take modifiers such as reverse and key, etc.

As far as I know, there is no other term than method to describe callable attributes.

8 Likes

Hi all,

So I am curious about why we would want to use either .sort() or sorted()over the other.

Is there a “more standard” option?

It seems like unless you are trying to play code golf, .sort() can do everything and more that sorted() can.

The biggest difference between the two is that one is a list method, list.sort() and the other is a global function. Only list objects have a sort attribute.

Another difference is that list.sort is insitu which means it does not create a copy, but sorts the list in place. It does not return anything (except None). This is not a method to use on an object passed to a function if we wish to preserve the original order.

sorted() on the other hand does create a copy and sorts that, then hands it off to the assignment variable. The original list is unaffected.

Because sorted is a global function, it can take any iterable and return a sorted list from that…

>>> sorted((3,7,4,9,2,1,7))
[1, 2, 3, 4, 7, 7, 9]
>>> sorted({'one':1, 'two':2,'three':3,'four':4,'five':5})
['five', 'four', 'one', 'three', 'two']
>>> sorted([3,7,4,9,2,1,7])
[1, 2, 3, 4, 7, 7, 9]
>>> sorted('this is a string')
[' ', ' ', ' ', 'a', 'g', 'h', 'i', 'i', 'i', 'n', 'r', 's', 's', 's', 't', 't']
>>> 

If we peer a little further down the rabbit hole we can learn a few more things about both the method and the function, in particular the optional arguments such as key and reverse but I’ll leave that for you to dig into.

Not really, since it depends upon the author’s aims and objectives. We make the choice depending on how we want things the be in the end.

If, for instance we are writing a median function that takes a sample which has a chronological order (last on is most recent) that we wish to preserve. We would not .sort() this in our function since that order would be lost. Instead,

s = sorted(sample)

where s is a sorted copy of sample but sample is unchanged.

15 Likes

Awesome, concise answer.

Thanks!

1 Like

use (reverse=True) inside sorted

1 Like

Here is an a detailed article about the topic:
https://www.afternerd.com/blog/sort-vs-sorted/

1 Like

Do you really think your statement is correct?

sorted() function will return a list so you must assign the returned data to a new variable.’

I dont think you need to assign it to a variable. you can just do print (sorted(keys)). Am I correct?

If all we want is to see the sorted list, and not do anything further in terms of computation, then print() is a viable approach. It will make a copy, sort it, print it, and then be gone from memory (or rather freed up for garbage collection). It really depends on the scenario.

1 Like

So, I get the difference between .sort() and sorted() BUT in the Computer Science lesson for “Working with Lists in Python: Sorting Lists II” it specifically says:

"A second way of sorting a list is to use sorted . sorted is different from .sort() in several ways:

1. It comes before a list, instead of after.
2. It generates a new list."

HOWEVER! When I try to create a variable for a sorted() list before creating the list itself I get this error:

“Traceback (most recent call last):
File “script.py”, line 1, in
games_sorted = sorted(games)
NameError: name ‘games’ is not defined”

Conclusion: I am either misreading the first difference between .sort() and sorted() OR definition 1 in this lesson is incorrect?

That is a strange way to describe the parameter of a built in function. Consider,

# before    after   =>   object -> method
#    \       /
    array.sort()  # no argument save for optional directives

    sorted(array) # 1 required positional argument
#     /      \
# before    after   =>  function -> argument
6 Likes

To add on to @mtf’s reply, I’d like to point out that the error you’re getting indicates that games has not been declared as a variable or is not accessible due to it being out of the scope of the level you are working at (though it is likely the former as the error occurs on the first line). Because sorted() requires a positional argument, that positional argument must exist or must be accessible, and games is not.

2 Likes

Thank you. I think you may be on to something! :grin:

Thank you for your very clear answer. Now I know a scenario in which I would use this it’s further cemented in my mind.

1 Like

Hello, I am just getting started with Python. Regarding the sort() vs sorted() argument, I understand sorted() will generate a new iterable, but what Python amateurs like me could benefit from knowing is that you can use sorted() to return the same iterable if you do not care about the original order, and further computation expects the iterable to be sorted. The explanations I found here and other places online seem to suggest it is not possible to sort an iterable “in place” with sorted(), as in numbers = sorted(numbers). Regardless if it is good or bad coding practice, I found it is possible to do so, and that is the part I feel is not clear.

@ajaxninja66418 said “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.”. This is true, but that new list returned by sorted() can have the same name and used for the same purposes.

If my amateur take is not correct, please correct me.

Thanks.