Contents

- Introduction
- Syntax – sorted()
- Example 1: sorted()
- sorted() with reverse – Ascending / Descending
- sorted() with key
- Limitations on Type of Items in Iterable with sorted() and key
- sorted() with lambda function as key
- sorted() with Custom Objects
- sorted() Function with Tuples
- sorted() Function with String
- sorted() Function with Sets
- Summary

## Python sorted() Built-in Function

sorted() built-in function sorts items of any iterable passed to it and returns sorted items in a list.

In this tutorial, we will learn the syntax of sorted() function, how to use it to sort items in iterable like list, set, tuple, etc.

### Syntax – sorted()

The syntax of sorted() function is

`sorted(iterable, key, reverse)`

where

**iterable**is any Iterable object. This is mandatory parameter.**key**is a function that can specifies the sorting criteria when sorted() sorts the items in the iterable.**reverse**is a boolean flag to specify the sorting order: ascending or descending

**key** and **reverse** are optional and keyword arguments.

sorted() function returns a List with the sorted items of given iterable. sorted() function does not try to modify the given iterable.

### Example 1: sorted()

Following is simple example program where we use sorted() built-in function to sort a list of numbers. We provide this list of numbers as iterable, and not provide key and reverse values as these are optional parameters.

**Python Program**

```
nums = [2, 8, 1, 6, 3, 7, 4, 9]
nums_sorted = sorted(nums)
print(nums_sorted)
```

Run **Output**

`[1, 2, 3, 4, 6, 7, 8, 9]`

### sorted() with reverse – Ascending / Descending

By default, sorted() function sorts the iterable in ascending order. But, you can specify the order by giving **reverse** named keyword to the sorted() function.

**reverse** is **False** by default, and the sorting order is ascending. If you provide `reverse = True`

, then the sorting order will be descending.

In the following example, we will sort the list of numbers in descending order.

**Python Program**

```
nums = [2, 8, 1, 6, 3, 7, 4, 9]
nums_sorted = sorted(nums, reverse = True)
print(nums_sorted)
```

Run **Output**

`[9, 8, 7, 6, 4, 3, 2, 1]`

If you give `reverse = False`

, the sorting happens in ascending order. As the default value of **reverse** is **True**, even if you do not provide `reverse = False`

, the sorting happens in ascending order.

**Python Program**

```
nums = [2, 8, 1, 6, 3, 7, 4, 9]
nums_sorted = sorted(nums, reverse = False)
print(nums_sorted)
```

Run **Output**

`[1, 2, 3, 4, 6, 7, 8, 9]`

### sorted() with key

We have already learnt that key is a function that specifies the sorting criteria.

sorted() function sorts the items of the iterable based on the values returned by **key **function for each item in the **iterable**.

Let us understand more about what **key **named parameter is, with some examples.

We know that len() is a built-in function that can be used to find the length of an **iterable**. In the following example program, we will use len() function as **key **for sorted() function, and sort the strings. As we are using len() as sorting **key**, items will be sorted based on their length.

**Python Program**

```
names = ['apple', 'banana', 'mango', 'orange', 'kiwi', 'plum', 'fig']
names_sorted = sorted(names, key = len)
print(names_sorted)
```

Run **Output**

`['fig', 'kiwi', 'plum', 'apple', 'mango', 'banana', 'orange']`

Strings with lesser length are on the left and strings with greater length are on the right of the sorted list.

Now, let us write a function that returns the number of vowels in the string. We will use this function as key to sort strings in the list.

**Python Program**

```
def vowels(x):
vowel_count = 0
for char in x.lower():
if char in ['a', 'e', 'i', 'o', 'u']:
vowel_count += 1
return vowel_count
names = ['apple', 'banana', 'mango', 'orange', 'kiwi', 'plum', 'fig']
names_sorted = sorted(names, key = vowels)
print(names_sorted)
```

Run **Output**

`['plum', 'fig', 'apple', 'mango', 'kiwi', 'banana', 'orange']`

First two strings have only one vowel, next three strings have two vowels and the last two strings have three vowels. Therefore the strings in the list are sorted based on the key function.

### Limitations on Type of Items in Iterable with sorted() and key

If you do not provide **key** named argument, the items are taken by value, as is, for comparison. So, all the items of the iterable should be of type that enable comparison with each other. If atleast an item in the iterable is not comparable with other, like if an item is string and others are numbers, then sorted() raises TypeError.

**Python Program**

```
nums = [2, 8, 1, 6, 'apple', 'watermelon']
nums_sorted = sorted(nums)
print(nums_sorted)
```

Run **Output**

```
Traceback (most recent call last):
File "example.py", line 2, in <module>
nums_sorted = sorted(nums)
TypeError: '<' not supported between instances of 'str' and 'int'
```

How do we fix this using key argument. For this specific example, the issue we are facing is that comparison operator less than, does not support one operand of type str and another of int.

If we want to sort integers by their value, and then the strings based on their length, we can write a function that returns length of string when the item is string, and the value itself, otherwise.

**Python Program**

```
def myFunc(x):
if isinstance(x, str):
return len(x)
else:
return x
nums = [2, 8, 1, 7, 'apple', 'watermelon']
nums_sorted = sorted(nums, key = myFunc)
print(nums_sorted)
```

Run **Output**

`[1, 2, 'apple', 7, 8, 'watermelon']`

`'apple'`

is of length 5. So it sorted to the position right in between `2`

and `7`

. `'watermelon'`

is of length 10, and so it it is sorted to the position after element `8`

.

### sorted() with lambda function as key

sorted() function takes a function for named parameter **key**. So, why not a lambda function for the **key**.

In the following example, we will try to use sorted() function to sort list of strings based on their length. In one of our previous examples, we have solved this problem by defining a function. But, in this example, we will give a lambda function as argument to the named parameter **key**.

**Python Program**

```
names = ['apple', 'banana', 'mango', 'orange', 'kiwi', 'plum', 'fig']
names_sorted = sorted(names, key = lambda name : len(name))
print(names_sorted)
```

Run **Output**

`['fig', 'kiwi', 'plum', 'apple', 'mango', 'banana', 'orange']`

### sorted() with Custom Objects

Based on our previous examples and case scenarios, it is evident that sorting does not depend mostly on what type of objects that an iterable has. But, it depends on what the **key** to sorting is, the function that decides how two objects in the iterable has to be compared.

In the following example, we define a class Fruit, and create a list of Fruit objects. Then we sort this list using sorted() based on a specified **key** function.

**Python Program**

```
class Fruit:
def __init__(self, name, count):
self.name = name
self.count = count
fruits = [Fruit('apple', 10),
Fruit('banana', 60),
Fruit('mango', 5),
Fruit('orange', 14),
Fruit('kiwi', 20),
Fruit('plum', 25),
Fruit('fig', 100)]
fruits_sorted = sorted(fruits, key = lambda fruit : fruit.count)
for fruit in fruits_sorted:
print(fruit.name, ',', fruit.count)
```

Run **Output**

```
mango , 5
apple , 10
orange , 14
kiwi , 20
plum , 25
banana , 60
fig , 100
```

Now, we see that the list of fruit objects have been sorted based on the fruit.count property which we specified using **key**.

### sorted() Function with Tuples

Tuple is an iterable, and in the following example, we will use sorted() function to sort items in tuple.

**Python Program**

```
mytuple = (3, 4, 1, 6, 2)
mytuple_sorted = sorted(mytuple)
print(mytuple_sorted)
```

Run **Output**

`[1, 2, 3, 4, 6]`

Please be noted that sorted() function returns the sorted items of given iterable as a list.

### sorted() Function with String

String is an ordered collection of characters. We will use sorted() function to sort the characters in string using sorted() function.

**Python Program**

```
mystring = 'apple'
mystring_sorted = sorted(mystring)
print(mystring_sorted)
```

Run **Output**

`['a', 'e', 'l', 'p', 'p']`

### sorted() Function with Sets

Set is an unordered collection of objects. We know that sorted() reads the elements from the iterable and sorts them to a list. In the following example, we initialize a set and sort the items in it using sorted() function.

**Python Program**

```
myset = {5, 8, 4, 3, 1, 6}
myset_sorted = sorted(myset)
print(myset_sorted)
```

Run **Output**

`[1, 3, 4, 5, 6, 8]`

### Summary

In this tutorial of Python Examples, we learned what sorted() function is, and how to use it in different scenarios, with the help of well detailed example programs.