Hi Pythonistas!

Today we are going to learn about the difference between **sort** and **sorted** in Python.

Consider the below example.

**Using sort function**

```
import random
import timeit
def sort_function():
a = list(range(1000_000_0))
random.shuffle(a)
return a.sort()
time_taken = timeit.timeit(sort_function, number=1)
print(“Time taken by sort function: ”, time_taken)
```

**Output**

`Time taken by sort function: 10.273957031000009`

**Using sorted function**

```
import random
import timeit
def sorted_function():
a = list(range(1000_000_0))
random.shuffle(a)
return sorted(a)
time_taken = timeit.timeit(sorted_function, number=1)
print(“Time taken by sorted function: ”,time_taken)
```

**Output**

`Time taken by sorted function: 10.785021954000058`

**The Reason**

The **sort** function takes **In-place** and the sorting does not require any additional memory or copying of the elements to a new list.

Whereas the **sorted** function sorts in a newly created list. Extra time is taken for the allocation and copying of elements to the list.

Let’s try to replicate the behavior of sorted by copying the new list and doing the sort function on the new list.

**Using under the hood function**

```
def sorted_function_under_the_hood():
a = list(range(1000_000_0))
random.shuffle(a)
b = a.copy()
return b.sort()
time_taken = timeit.timeit(sorted_function_under_the_hood, number=1)
print(“Time take by the under the hood function: ”, time_taken)
```

**output**

`Time take by the under the hood function: 10.700373989000127`

We can see that the time taken by sorted and the underhood function are very close.

**Comparison summary**

Function name |
Pros |
Cons |

Sort |
faster No additional memory |
Work only for list Cannot be used if we need to maintain the order of input |

Sorted |
Work for any iterable Doesn't affect the input |
Slower Additional memory required |

Use the sort or sorted function according to your datatype.

Hope you have learned something from this post. Please share your valuable feedback to afsal@parseltongue.co.in