Difference between sort vs sorted Python Function

You can sort the list using the sort() or sorted() Python function. You must be thinking about then what is the difference between sort() and sorted() function.

The main difference between the list sort() and sorted() Python function is that the sort() the 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. 

Let’s see How both used and their syntax:-

 sorted(list)

vs

list.sort()
  • list.sort mutates the list in place & returns None
  • sorted takes any iterable & returns a new list, sorted.

So you can understand 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.

Example between sort vs sorted Python Function

Sorted() Function

sorted(iterable, key=key, reverse=reverse)

Code

number_list = [1, 3, 2, 4]
 
print(sorted(number_list))

Output: [1, 2, 3, 4]

Read more: Python sorted function | Sort string, list, tuple, dictionary

sort() Function

list.sort(reverse=True|False, key=myFunc)

code

numbers = [5, 3, 4, 2, 1]
 
# Sorting list of Integers in ascending 
numbers.sort()
 
print(numbers)

Output: [1, 2, 3, 4, 5]

Read more: Python sort list (Array) | sorted function – Strings (alphabetically), Number, list

All common sort vs sorted python Questions

Here are some common doubt between sort() vs sorted() function in python:-

1. When is one preferred over the other?

Answer: Use list.sort() when you want to mutate the list sorted() when you want a new sorted object back. Use sorted() when you want to sort something that is an iterable object, not a list yet.

2. Which is more efficient? By how much?

Answer: For lists, list.sort() is faster than sorted() because it doesn’t have to create a copy. For any other iterable object, you have no choice.

3. Can a list be reverted to the unsorted state after list.sort() has been performed?

Answer: No, you cannot retrieve the original positions. Once you called list.sort() the original order is gone.

Do comment if you know any other differences and doubts about this tutorial.

Note:
IDE: PyCharm 2020.1.1 (Community Edition)
macOS 10.15.4
Python 3.7
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.