Python sorted() function returns a sorted list from the items in the iterable.

## Python sorted() function

Python sorted() function syntax is:

1 2 3 |
sorted(iterable, *, key=None, reverse=False) |

There are two optional arguments – key and reverse – which must be specified as keyword arguments.

**iterable**: elements from the iterable will be sorted. If key is not specified then natural sorting is used for the elements.**key**: specifies a function of one argument that is used to extract a comparison key from each list element.**reverse**: optional boolean argument. If specified as True then elements are sorted in reverse order.

## Python sorted() string

String is iterable in Python, let’s see an example of using sorted() function with string argument.

1 2 3 4 |
s = sorted('djgicnem') print(s) |

Output: `['c', 'd', 'e', 'g', 'i', 'j', 'm', 'n']`

## Python sorted() reverse

Let’s see the sorted list when reversed is passed as True.

1 2 3 4 |
s = sorted('azbyx', reverse=True) print(s) |

Output: `['z', 'y', 'x', 'b', 'a']`

## Python sorted() tuple

1 2 3 4 5 6 |
s = sorted((1, 3, 2, -1, -2)) print(s) s = sorted((1, 3, 2, -1, -2), reverse=True) print(s) |

Output:

1 2 3 4 |
[-2, -1, 1, 2, 3] [3, 2, 1, -1, -2] |

## Python sorted() key

Let’s say we want to sort a sequence of numbers based on their absolute value, we don’t care about their being positive or negative. We can achieve this by passing `key=abs`

to sorted() function. Note that abs() is the built-in function that returns the absolute value of the number.

1 2 3 4 |
s = sorted((1, 3, 2, -1, -2), key=abs) print(s) |

Output: `[1, -1, 2, -2, 3]`

## Python sort list

Let’s see some examples of using sorted() function with list.

1 2 3 4 5 6 7 8 9 10 |
s = sorted(['a', '1', 'z']) print(s) s = sorted(['a', '1b', 'zzz']) print(s) s = sorted(['a', '1b', 'zzz'], key=len) print(s) s = sorted(['a', '1b', 'zzz'], key=len, reverse=True) print(s) |

Output:

1 2 3 4 5 6 |
['1', 'a', 'z'] ['1b', 'a', 'zzz'] ['a', '1b', 'zzz'] ['zzz', '1b', 'a'] |

## sorted() vs list.sort()

- sorted() function is more versatile because it works with any iterable argument.
- Python sorted() function builds a new sorted list from an iterable whereas list.sort() modifies the list in-place.

## sorted() with iterable of different element types

Let’s see what happens when we try to use sorted() function with iterable having different element types.

1 2 3 |
s = sorted(['a', 1, 'x', -3]) |

Output:

1 2 3 4 |
TypeError: '<' not supported between instances of 'int' and 'str' <img class="alignnone wp-image-22593 size-full" src="https://all-learning.com/wp-content/uploads/2018/09/Python-sorted-functions.png" alt="Python sorted() function" width="1200" height="628" /> |

## sorted() with custom objects

We can use sorted() function to sort a sequence of custom object based on different types of criteria.

Let’s say we have an Employee class defined as:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class Employee: id = 0 salary = 0 age = 0 name="" def __init__(self, i, s, a, n): self.id = i self.salary = s self.age = a self.name = n def __str__(self): return 'E[id=%s, salary=%s, age=%s, name=%s]' % (self.id, self.salary, self.age, self.name) |

Now we have a list of employee objects as:

1 2 3 4 5 6 |
e1 = Employee(1, 100, 30, 'Amit') e2 = Employee(2, 200, 20, 'Lisa') e3 = Employee(3, 150, 25, 'David') emp_list = [e1, e2, e3] |

**Sort list of employees based on id**

1 2 3 4 5 6 7 |
def get_emp_id(emp): return emp.id emp_sorted_by_id = sorted(emp_list, key=get_emp_id) for e in emp_sorted_by_id: print(e) |

Output:

1 2 3 4 5 |
E[id=1, salary=100, age=30, name=Amit] E[id=2, salary=200, age=20, name=Lisa] E[id=3, salary=150, age=25, name=David] |

**Sort list of employees based on age**

1 2 3 4 5 6 7 |
def get_emp_age(emp): return emp.age emp_sorted_by_age = sorted(emp_list, key=get_emp_age) for e in emp_sorted_by_age: print(e) |

Output:

1 2 3 4 5 |
E[id=2, salary=200, age=20, name=Lisa] E[id=3, salary=150, age=25, name=David] E[id=1, salary=100, age=30, name=Amit] |

## Summary

Python sorted() function is guaranteed to be stable. It’s very powerful and allows us to sort a sequence of elements based on different keys.

Reference: Official Documentation