Python: Sort vs Sorted

In Python, you can use sort or sorted to sort a list.

But what is the difference between the two? This is what I will discuss in this article.

First: Sorting a Python List using Sort

sort() is a method on the list object.

Say, you have an arbitrary list L and you want to sort it. Here is what you can do.

``````>>> L = [5, 3, 7]
>>> L.sort()
>>> L
[3, 5, 7]``````

There is one thing that I want to notice: L was sorted in-place. This means that no new lists were created.

You can double check that using the id built-in function.

``````>>> L = [5, 3, 7]
>>> id(L)
4477543040
>>> L.sort()
>>> L
[3, 5, 7]
>>> id(L)
4477543040``````

Having the same id means that the location of the object is the same before and after sorting, which confirms that sorting happened in-place.

Second: Sorting a Python List using Sorted

Unlike sort, sorted is not a method.

sorted() is a built-in function like print() or id().

Let’s try to use sorted to sort the same list from above.

``````>>> L = [5, 3, 7]
>>> sorted(L)
[3, 5, 7]
>>> L
[5, 3, 7]``````

It doesn’t seem to work, does it? It looks like L hasn’t changed. Why is that?

Unlike sort, sorted creates a new list object and sorts the elements of the original list L in this new object without modifying the original list.

This is an essential difference between sort and sorted.

You can easily confirm that by inspecting the ids.

``````>>> L = [5, 3, 7]
>>> id(L)
4477542848
>>> id(sorted(L))
4477542976``````

So with that in mind, the correct way to use sorted is as follows:

``````>>> L = [5, 3, 7]
>>> Q = sorted(L)
>>> Q
[3, 5, 7]``````

So essentially, if you want to sort the elements of a list in place, use the sort method. But if you want to sort the items of a list in a new list object without modifying the original list, use the sorted built-in function.

What sorting algorithm is used for sort and sorted?

Both sort and sorted use the Timsort sorting algorithm which is a hybrid sorting algorithm between merge sort and insertion sort.

If you want to know more about Timsort and its superior performance, then I highly recommend reading this.

Learning Python?

Check out the Courses section!

Are you Beginning your Programming Career?

I provide my best content for beginners in the newsletter.

• Python tips for beginners, intermediate, and advanced levels.
• CS Career tips and advice.
• Special discounts on my premium courses when they launch.

And so much more…

Subscribe
Notify of