# Difference between sort and sorted in python ## Introduction

Both the sort method and the sorted function are used for, as the name suggests, sorting purposes in python. They share similarities, as well as differ on some features and use cases.

## The Sort Method in Python

The sort method is a built-in python method that modifies the list in-place and returns None. By default, strings are sorted alphabetically, and numbers are sorted numerically, Meaning in ascending order.

### Sorting a list

``````list1 = [2,6,3,5,1,4]
list1.sort()
print(list1)
# [1,2,3,4,5,6]``````

Notice how we didn’t assign list1.sort() to a new variable.

However, when ordering a list, we usually want to keep the original, that is why this method is less used compared to the sorted function.

## The Sorted function in Python

The built-in sorted function also sort a list, but unlike the sort, it builds a new sorted list from an Iterable which is a key difference between the two, sort only sort lists while sorted returns a sorted list from an Iterable, meaning any object that can be looped over such as lists, sets, dictionaries, lists, tuples, sets, dictionaries, strings, etc, strings, etc.

### Sorting a list

``````list1 = [2,6,3,5,1,4]
list2 = sorted(list1)
print(list2)
# [1,2,3,4,5,6]``````

Notice how in this case we assigned the results to a new variable called list2, and if we check list1 we find that it didn’t change.

``````print(list1)
# [2,6,3,5,1,4]``````

### Sorted() can sort Iterables not just lists!

Let’s se some examples on how we can sort Iterables in python using the sorted method.

### Sorting a dictionary

First let se how to sort a dictionary and return keys:

``````sorted({2: 'Tom', 4: 'James', 3: 'Natasha', 5: 'Bella', 1: 'Chris'})
# [1, 2, 3, 4, 5]``````

Now, lets sort a dictionary based on key and return both key and value in list of tuples:

``````sorted({2: 'Tom', 4: 'James', 3: 'Natasha', 5: 'Bella', 1: 'Chris'}.items(), key=lambda x:x)
# [(1, 'Chris'), (2, 'Tom'), (3, 'Natasha'), (4, 'James'), (5, 'Bella')]``````

We can also sort a dictionary based on value and return both key and value in list of tuples:

``````sorted({2: 'Tom', 4: 'James', 3: 'Natasha', 5: 'Bella', 1: 'Chris'}.items(), key=lambda x:x)
# [(5, 'Bella'), (1, 'Chris'), (4, 'James'), (3, 'Natasha'), (2, 'Tom')]``````

### Sorting an object

Let’s create a custom Employee class, instantiate some objects add them to a list, and then sort that list based on an attribute:

``````class Employee:
def __init__(self, name, department, salary):
self.name = name
self.department = department
self.salary = salary
def __repr__(self):
return repr((self.name, self.department, self.salary))

Employees_objects = [
Employee('James', 'A', 85000),
Employee('Riley', 'D', 55000),
Employee('Kevin', 'B', 70000),
]

print(sorted(Employees_objects, key=lambda employee: employee.salary))
# [('Riley', 'D', 55000), ('Kevin', 'B', 70000), ('James', 'A', 85000)]``````

Note that we used the key parameter in this example to make it work since our class doesn’t support comparaison directly. We will talk about the key parameter in the complex sorting section.

Now that we saw the differences, let’s see more common features between the sort method, and sorted function.

## Reverse sorting in python – reverse parameter

Both the sorted function and the sort method accepts a reverse parameter that is set to False by default. If we set it to True, we get ordering reversed, meaning in Descending order.

``````list1 = [2,6,3,5,1,4]
list2 = sorted(list1, reverse=True)
print(list2)
# [1,2,3,4,5,6]``````

Notice how the sorting order is reversed.

## Complex sorting in python – key parameter

Both sort and sorted have a key parameter to specify any function (or another callable) that will be called on each list element before making the sorting comparaison. Meaning that we add a criteria to the comparaison.

For example, if we sort a list that only contains uppercase and lowercase letters, Python would sort uppercase ones and put them first, then sort lower case ones and put them after.

``````list3 = [ 'B','a','C','A','c','b']
print(sorted(list3))
# ['A', 'B', 'C', 'a', 'b', 'c']``````

Now let sorting the same list with an addition parameter key=str.upper

``````print(sorted(list3, key=str.upper))
# ['a', 'A', 'b', 'B', 'c', 'C']
``````

As you can see, python treated all letters as uppercase letter, that’s why lowercase “a” comes before uppercase “B” since python teated them not as lowercase “a” and uppercase “B”, but both as uppercase (“A” and “B”).

The value of the key parameter should be a function (or other callable) that takes a single argument and returns a key to use for sorting purposes. This technique is fast because the key function is called exactly once for each input record.

Now that we understood how the key works, we can see how we can use it for complex sorting.

Let’s see another example using the lambda function. This is a common example where we need to sort an Iterable using a specific index.

``````employee_tuple = [
('Mark', 'A', 80000),
('Amir', 'B', 60000),
('Sara', 'C', 50000),
]
sorted(employee_tuple, key=lambda employee: employee)
# [('Sara', 'C', 50000), ('Amir', 'B', 60000), ('Mark', 'A', 80000)]``````

As we can see, the list is sorted based on the index number 2 of the inside tuples (50000, 60000, and 80000). Let’s sort based on index number 1 (‘A’, ‘B’ and ‘C’):

``````employee_tuple = [
('Mark', 'A', 80000),
('Amir', 'B', 60000),
('Sara', 'C', 50000),
]
sorted(employee_tuple, key=lambda employee: employee)
# [('Mark', 'A', 80000), ('Amir', 'B', 60000), ('Sara', 'C', 50000)]``````

## Conclusion

In the majority of use cases you will find yourself using the sorted function over the sort method due to the preservation of the original list and sorting all kind of Iterables.

Always put the key argument in mind since it allows us to sort complex objects.