# Difference between sort vs sorted Python Function

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

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

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

vs

• `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

#### Sorted() Function

Code

Output: [1, 2, 3, 4]

### sort() Function

code

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

### 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 difference and doubts on 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.

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