Python is a powerful language that offers a wide range of built-in functions and modules to facilitate programming. We can use these functions according to their applications. One of these functions is sorted(), which is used to sort iterable objects in ascending or descending order. In this article, we will explore the sorted() function in Python and its various features and applications.

## Python Sorted() Function

The sorted() function is a built-in function in Python that takes an iterable object as an argument and returns a new list with its elements sorted in ascending order by default. It can also sort the elements in descending order by passing the reverse=True parameter.

Assume you are given the task of sorting a string according to the Unicode value of the characters. Since the sort() function fails when applied to strings, you must use a function that is compatible with all iterable objects in Python. Thus, the sorted() method in Python is now available, which will quickly arrange the text according to the ASCII value of the letters.

So why would you write all that code when you can use the built-in method to keep the sorted list in a variable? Depending on the kind of values provided in the iterable object, an ordered list may contain string values, integers, or other types of values.

If the iterable contains numeric values, sorting will be carried out from small to large according to the value of the numbers, and if the iterable contains character values, the ordered list will contain strings arranged according to their ASCII values.

The python sorted function is used to return a freshly made sorted list from an iterable object and keep that freshly made list in a variable, as the function’s name implies.

### Syntax of Python Sorted Function

The syntax for using the python sorted function is given below:

`sorted(iterable, key=None, reverse=False)`

### Parameter of the Python Sorted Function

The parameters of the python sorted functions are given below:

**Iterable:**It is the iterable object to be sorted, such as a list, tuple, or string.**Key:**It is an optional function that can be used to customize the sorting order. It takes a single argument and returns a value that will be used to determine the sorting order.**Reverse:**It is an optional Boolean parameter that determines whether the sorting order should be reversed. If True, the elements will be sorted in descending order.

### Return Type of Python Sorted Function

The return type of the python sorted function is a sorted list and the list is according to iterable passed, a list, dictionary tuple.

## Examples of Python Sorted Function

Now, we will understand the python sorted function with the help of various examples.

**Example 1 of Python Sorted Function: Sorting a List**

Below is the code and implementation of the above-mentioned example.

**Code Implementation**

numbers = [5, 2, 8, 1, 6] sorted_numbers = sorted(numbers) print(sorted_numbers)

**Output**

`[1, 2, 5, 6, 8]`

**Explanation of the above code**

In this example, we first define a list of numbers and assign it to the variable numbers. We then call the sorted() function and pass the numbers list as an argument. The function returns a new sorted list, which we assign to the variable sorted_numbers. Finally, we print the sorted list to the console.

**Example 2 of Python Sorted Function: Sorting a String**

The sorted() function can also be used to sort a string in Python. When sorting a string, the function treats it as a list of characters. Given below are the code and output of the above-mentioned example.

**Code Implementation**

word = 'prepbytes' sorted_word = sorted(word) print(sorted_word)

**Output**

`['b', 'e', 'e', 'p', 'p', 'r', 's', 't', 'y']`

**Explanation of the above code**

In this example, we define a string variable word and assign it the value ‘python’. We then call the sorted() function with the word as an argument, which returns a new sorted list of characters. We assign this list to the variable sorted_word and print it to the console.

**Example 3 of Python Sorted Function: Customizing the sorting order using key parameter**

The key parameter of the sorted() function allows us to customize the sorting order. It takes a function that is applied to each element in the iterable, and the values returned by the function are used to determine the sorting order.

**Code Implementation**

names = ['Alice', 'bob', 'Charlie', 'dave'] sorted_names = sorted(names, key=str.lower) print(sorted_names)

**Output**

`['Alice', 'bob', 'Charlie', 'dave']`

**Explanation of the above code**

In this example, we define a list of names and assign it to the variable names. We then call the sorted() function and pass names as the first argument and the str.lower method as the key argument. The str.lower method converts all the strings to lowercase before sorting. This ensures that the sorting order is not affected by the case of the letters in the names.

**Example 4 of Python Sorted Function: Sorting in Descending Order**

The sorted() function in Python can sort elements in ascending order by default. However, you can also use it to sort elements in descending order by passing the reverse=True parameter.

**Code Implementation**

numbers = [5, 2, 8, 1, 6] sorted_numbers = sorted(numbers, reverse=True) print(sorted_numbers)

**Output**

`[8, 6, 5, 2, 1]`

**Explanation of the above code**

In this example, we define a list of numbers and assign it to the variable numbers. We then call the sorted() function and pass the numbers list as the first argument and the reverse=True parameter as the second argument. This will sort the numbers in descending order.

## Applications of Sorted Function

The sorted() function is a versatile tool in Python that can be used for a wide range of applications. Here are some specific use cases for the sorted() function:

**Sorting lists and tuples:**The most common use of the sorted() function is to sort lists and tuples in ascending or descending order. This is useful for a wide range of applications, including data analysis, scientific computing, and web development.**Sorting dictionaries:**The sorted() function can also be used to sort dictionaries based on their keys or values. This is useful for sorting data in a specific order or for generating reports and summaries.**Sorting complex objects:**The sorted() function can be used to sort complex objects, such as lists of objects, tuples of objects, or dictionaries of objects. This is useful for sorting data based on multiple criteria or for custom sorting algorithms.**Sorting by multiple criteria:**The sorted() function can be used to sort data based on multiple criteria. For example, you can sort a list of employees by their last name and then by their first name.**Sorting by key function:**The sorted() function can be used to sort data based on a custom key function. This is useful for sorting data based on complex rules or for sorting data that cannot be easily sorted using built-in Python functions.

**Conclusion**

The python sorted function is a powerful tool for sorting iterable objects in Python. You can use it to sort elements in ascending or descending order based on specific criteria using the key and reverse parameters. By mastering this function, you can efficiently sort various data structures in your Python programs.

## Python Sorted Function – FAQs

**1. What is the purpose of the Python sorted() function?**

The Python sorted() function is used to sort a given iterable object (list, tuple, set, dictionary, etc.) in ascending or descending order.

**2. What is the reverse parameter in the sorted() function?**

The reverse parameter is an optional parameter that specifies whether the sorting order should be in ascending or descending order. The default value is False (ascending order), and if set to True, the items will be sorted in descending order.

**3. Can we use the sorted() function on a dictionary?**

Yes, we can use the sorted() function on a dictionary, but it will return a list of sorted keys or a list of tuples containing key-value pairs, depending on how we use it.

**4. What is the time complexity of the sorted() function?**

The time complexity of the sorted() function is O(n log n) in the average case and worst case, where n is the length of the iterable object being sorted.