# Python sorted() function

In this post, we will see about Python sorted() function.
Python sorted() function returns sorted list from the iterable.
You can sort either in ascending or descending order using this function.

## Syntax

iterable: Iterable is parameter which can be iterable(list etc) or iterable object.
key: It is optional parameter and can be used as function for the comparison.
reverse: It is also optional parameter and can be either True or False. If reverse=true then iterable will be sorted in reversed order.

## Return

It returns the sorted list from the iterable .

## Example

### Sorting list, tuple or set

Let’s see a very simple example:

``` l= [23,10,21,56,34,45,89,12] print("Sorted list: ",sorted(l)) # Sorted list with reverse=true print("Sorted list in reverse order: ",sorted(l,reverse=True)) t=(34,2,11,3,56,7,35) print("Sorted tuple: ",sorted(t)) s=set([5,5,5,4,3,3,1,2,1,2,3,2,3,4,4]) print("Sorted set: ",sorted(s)) ```

Output:

Sorted list: [10, 12, 21, 23, 34, 45, 56, 89]
Sorted list in reverse order: [89, 56, 45, 34, 23, 21, 12, 10]
Sorted tuple: [2, 3, 7, 11, 34, 35, 56]
Sorted set: [1, 2, 3, 4, 5]

### Sorting dictionary, frozenset or string

Let’s see a very simple example:

``` s=frozenset([40,40,30,20,10,10,20]) print("Sorted frozenset: ",sorted(s)) d={'z':1,'x':2,'y':3} print("Sorted Dictionary: ",sorted(d)) st='code2master' print("Sorted String: ",sorted(st)) ```

Output:

Sorted frozenset: [10, 20, 30, 40]
Sorted Dictionary: [‘x’, ‘y’, ‘z’]
Sorted String: [‘2’, ‘a’, ‘c’, ‘d’, ‘e’, ‘e’, ‘m’, ‘o’, ‘r’, ‘s’, ‘t’]

### Sort using key function

We are going to sort list of tuples based on key function.

``` employee_tuples = [ ('John', 29), ('Mary', 19), ('Martin', 40) , ('Sam', 30)] def ageAsKey(t): return t[1] print("Sorted by age:",sorted(employee_tuples, key=ageAsKey)) # sort by age ```

Output:

Sorted by age: [(‘Mary’, 19), (‘John’, 29), (‘Sam’, 30), (‘Martin’, 40)]

You can use lambda expression as well here.

``` employee_tuples = [ ('John', 29), ('Mary', 19), ('Martin', 20) , ('Sam', 30)] print("Sorted by name:",sorted(employee_tuples, key=lambda t:t[0])) # sort by name ```

Output:

Sorted by name: [(‘John’, 29), (‘Martin’, 20), (‘Mary’, 19), (‘Sam’, 30)]

That’s all about Python sorted() function.