Difference between sort() and sorted() function in Python

Initially i was confused as to what is the difference between sort() and sorted(), but with a little bit of hacking and playing around with code, I was able to remove my confusion. I’m also attaching the code I used as a part of my operations on lists. In this blog post, i’ll deconstruct sort() and sorted() functions.
The most basic difference is, list_name.sort() function works on the list in place and it physically sorts the elements of the list, while sorted(list_name) function simply returns the sorted form of the list without actually physically sorting the list.
(Excuse me for not using any technical jargons here).

Try running this fun script with Python.
Try running this fun script with Python.

Hence, list.sort() is less convenient than sorted() function because the original order in the list is not preserved, but it is slightly more efficient that sorted(), so go for it if you don’t need to preserve the original list.
This difference arises because of an extra copying step need in sorted() function so that the original order is preserved.
The psuedo-code for sorted() would be:-
def sorted(iterables, key, reverse)
s=list(iterables)  #Copying into a new list
return s

On the other hand, sort() directly does in-place sorting.

The built-in sorted() function is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal.

Another important difference is that, sorted() function works on all kinds of iterables, whereas sort is available only on lists! Check out this page to make this more clear,”

NOTE: In the background, both the functions use the same sorting algorithm called timsort. (Desgined by Tim Peters)
Look at the psuedocode once again, even sorted() calls the sort() function after copying the iterables to a list. You can find the documentation for the same here at, https://github.com/python/cpython/blob/434673580106f4391da2c8937e646be579bc0c4d/Objects/listsort.txt

Other links to make the difference more clear:-




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s