Difference between sort() and sorted() in Python

In this article, we would cover the difference between sort() and sorted() methods in Python. sort() and sorted() are two methods which are used to sort the contents of an iterable. We already have discussed the two in the following articles –

  1. sort and reverse sort in Python and,
  2. sorted() in Python.

Do check these two articles, we consider this article to be an extension of the above mentioned articles.

The Differences

I. sort() method basically works with lists whereas sorted() method can be used with any iterable be it – dicts, tuples, lists etc.

II. Apart from that, when we use sort() method to sort elements of a list. The sorting happens on the same list i.e. no new list is created and modifications takes place in the original list. Whereas, with sorted() method, a new list is created. And, the sorted elements are put in the new list. This leaves the original iterable intact.

Examples

Furthermore, let’s see what happens when we use tuple iterable, x. First, we will use the sorted() method –

x=("k","x","a")

Use sorted() method to sort –

y=sorted(x)

To see the output –

y

This would return with –

['a', 'k', 'x']

Notice here that, we got the list as output. Now, let’s see what happens when we try to use the sort() method on a tuple. We will continue the same example –

x=("k","x","a")

sort() method to sort –

x.sort()

At this stage, we will get an error –

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'sort'

Therefore, the correct way would be to use a list instead of a tuple when using sort() method. So, we try again but this time with a list, x

x=["k", "x", "a"]

sort() method to sort –

x.sort()

Lastly, to see the output –

x

This would return with –

['a', 'k', 'x']

See, in both cases, the output is a list.

Similar Posts