# What is Python sorted() Function?

Python `sorted()`

is a built-in function that you’ll find really handy in your codes. It’s designed to help you `sort`

iterable objects like `lists`

, `tuples`

, and `strings`

. When you use `sorted()`

, it gives you a new `sorted`

list with the elements from your original `iterable`

, sorted either in `ascending`

or `descending`

order.

Depending on your needs, you can customize the `sorting`

process using optional keyword arguments like `key`

to define specific `sorting`

criteria within your elements and `reverse`

to control whether you want the sorting order to be `ascending`

(which is the default) or `descending`

. This function is a fantastic tool to keep in your coding arsenal for `sorting`

and organizing data easily.

To get more clear picture of `Python sorted()`

function let’s imagine you’re in a bustling marketplace, and you want to arrange your items in `order`

. The Python `sorted()`

function is your trusted helper—it sorts `data`

, whether it’s a list of `numbers`

, a collection of `names`

, or any other `iterable`

, making your life easier.

Now that you have a grasp of the fundamental aspects of the Python `sorted()`

, let’s examine its syntax and parameters, which hold significant importance for efficiently running the provided examples.

## Python sorted() Syntax and Parameters

The syntax of the `sorted()`

function is refreshingly straightforward. It involves invoking the function and providing an iterable as its input, as shown in the following format:

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

When you’re working with the Python `sorted()`

function, it’s important to note that it requires `three`

parameters. The first one is mandatory, and it’s called the `iterable`

or `sequence`

, which is the collection of items you want to `sort`

. The other two parameters, `key`

and `reverse`

, are `optional`

. Now, let’s take a closer look at these parameters to get a better grasp of how they function.

### I. Iterable (mandatory)

The `iterable`

parameter represents a sequence such as `string`

, `tuple`

, or a collection like a `set`

, `dictionary`

, or `frozen set`

, or any other kind of iterator that you provide.

### II. Key (optional)

The `key`

parameter, when set to `True`

, reverses the sorted list, which means it sorts the list in descending order. If you don’t provide this parameter, it defaults to `False`

.

### III. Reverse (optional)

The `reverse`

parameter is a function that acts as a reference point for sorting comparisons. If you don’t specify this parameter, it defaults to `None`

.

Having a solid understanding of Python `sorted()`

syntax and parameters, let’s explore its return value to see how it works in practical scenarios.

## Python sorted() Return Value

The return value of the Python `sorted()`

is a fresh list that contains all the elements extracted from the original iterable (`sequence or collection`

). By default, these elements are sorted in `ascending`

order, but you can alter the sorting order. Importantly, the original `iterable`

remains unaltered, ensuring that your original data structure remains intact while providing you with a sorted version of its contents. Consider the following illustration:

In this example, we start with an `unsorted`

list of numbers called `unsorted_numbers`

, which contains [`5`

, `2`

, `9`

, `1`

, `5`

]. Our aim is to arrange this list in `ascending`

sequence.. To do this, we use the `sorted()`

function.

We pass our `unsorted_numbers`

list as an argument to the `sorted()`

function, which creates a new list called `sorted_numbers`

containing the same elements but sorted in ascending order. Finally, we print `sorted_numbers`

, by using `print()`

function.

As showcase in the example above, you can efficiently arrange the items within a list by employing the Python `sorted()`

function.

As previously stated, the `sorted()`

function is primarily utilized for sorting tasks. Now, let’s move on and examine practical scenarios where the Python `sorted()`

function comes into play in different situations.

### I. Python sorted() with String

In Python, When you apply `sorted()`

to a `string`

, it organizes the individual characters within the `string`

according to their `alphabetical`

order, akin to arranging words in a `dictionary`

. This functionality is particularly useful if you’re a linguist investigating the occurrence of `letters`

in a sentence.

In this context, the `sorted()`

function serves as your linguistic instrument, enabling you to `arrange`

the letters in alphabetical order for meticulous analysis. Here’s an example of how you can use `sorted()`

with a `string`

:

Here, we have a sentence stored in the variable `sentence`

, which reads, `Python is the most popular programming language`

. To analyze and manipulate the `sentence`

, we decided to use Python’s `sorted()`

function. It’s a handy tool that can sort elements in a `sequence`

, like characters in a `string`

, and return a new sequence with those elements `arranged`

in a specific `order`

.

So, we applied the `sorted()`

function to our `sentence`

. This meant taking each character in the `sentence`

and sorting them `lexicographically`

, much like arranging words in a `dictionary`

. The `result`

, which we stored in the variable `sorted_sentence`

, is a list containing all the characters from the original `sentence`

but sorted in `alphabetical`

order. To see the sorted `result`

, we used the `print()`

function to display `sorted_sentence`

. When we run the code, it will print the characters from our sentence sorted `alphabetically`

on the screen.

This is helpful if you want to analyze the characters in the sentence in a different `order`

, perhaps for further linguistic or computational processing.

### II. Python sorted() in Descending Order

You can also `sort`

elements in `descending`

order in Python by using the `sorted()`

function and specifying the `reverse`

parameter as `True`

. By default, when you use `sorted()`

, it arranges elements in `ascending`

order. However, when you set `reverse=True`

, the function will arrange the elements in `descending`

order. This can be particularly useful when you need to `reverse`

the elements in which data is sorted. To illustrate, here’s an example:

For this example, we have a tuple called `vintage_years`

, which contains a series of `years`

denoting different vintage points: `1960`

, `1975`

, `1985`

, `1995`

, and `2005`

. Our goal here is to `sort`

these years in `descending`

order, so we know the most recent `vintage`

years first. To do this, we’ve used Python’s `sorted()`

function.

First, we decided to sort `vintage_years`

in `reverse`

order, and we accomplished this by setting the `reverse`

parameter to `True`

within the `sorted()`

function. Once we’ve sorted the years, we want to display the result to the `user`

. So, we used the `print()`

function to output the years, which are stored in the variable `sorted_years_desc`

. When we run this code, it will print `Reversed years are`

: followed by the `years`

sorted in backward order, allowing us to see the vintage years in reverse `chronological`

order.

This technique leverages the flexibility and simplicity of Python `sorted()`

, allowing you to efficiently manipulate and display your data in the desired way.

### III. Python sorted() with len()

Python `sorted()`

can be employed alongside the `len()`

function to arrange a group of elements according to their `size`

, whether it’s the number of `items`

they contain or the characters within each `element`

. This can be a valuable technique, especially when dealing with `lists`

of `strings`

or other `sequences`

, where you may want to organize them in a way of their `lengths`

. To showcase this approach, consider the following example:

In this example, we have a `set`

called `books`

that contains the `titles`

of various `books`

. Our goal is to sort these book `titles`

based on their `lengths`

, arranging them in an order. To achieve this, we’ve used Python’s `sorted()`

function and provided the `key=len parameter`

, indicating that we want to classify the `titles`

based on the `length`

. After sorting, we’ve created a new set called `sorted_books_by_length`

to store the sorted `titles`

. This set now contains the book titles organize from `shortest`

to `longest`

.

To display the result, we use the `print()`

function, which shows the contents of the `sorted_books_by_length`

set. This allows us to see the book titles organized by their respective `lengths`

.

As a result, the above example provides you with an organized and ordered set of book `titles`

, helping you better understand and manipulate the information based on the `lengths`

.

### IV. Python Sorted() with Lambda

In Python, you can use the `sorted()`

function with a `lambda function`

to categorize a collection of elements based on a `custom`

criterion defined by the `lambda`

function. This allows you to classify elements in a way that may not be achievable using the default sorting behavior. For instance:

Here, we have a collection of `data`

points stored in a variable called `data_points`

. Each data point consists of a pair of `values`

, where the `first`

value represents one aspect of the `data`

, and the `second`

value represents `another`

aspect. In our specific case, the `data`

points are as follows: (`3, 4`

), (`1, 2`

), (`5, 1`

), and (`2, 3`

).

Our goal here is to arrange these `data`

points based on the `second`

value of each `pair`

, meaning we want to rearrange them in an order of the `second`

aspect of the `data`

. To achieve this, we use the `sorted()`

function. Then we’re using a `lambda`

function as the `key`

parameter. This `lambda`

function takes an individual data point `x`

and returns `x[1]`

, which means it’s telling the `sorted()`

function to organize the `data`

points based on their `second`

values.

After applying the `sorted()`

function to our `data_points`

, we store the result in a variable called `sorted_data`

. So, `sorted_data`

now contains the sorted `data`

points. Next, we have the line `tuple_sort = (sorted_data)`

. This line is creating a new variable called `tuple_sort`

and assigning it the value of `sorted_data`

. Finally, we print the `tuple_sort`

variable, which contains the data points sorted in `ascending`

order of their `second`

values.

It illustrates the use of the `sorted()`

function with a custom sorting `key`

, achieved through a `lambda`

function, to manipulate and organize data.

## Python sorted Advanced Examples

In the upcoming section, we’ll explore various advanced instances of the Python `sorted()`

function, showcasing its flexibility and extensive array of uses.

### I. Python sorted() with Conditional Statements

The `sorted()`

function, when used with `conditional statements`

through the `key`

parameter, allows you to organize elements from an `iterable`

, based on custom defined by a provided function. This function, often implemented as a `lambda`

function or a `custom`

function, calculates a value for each element, and `sorted()`

arranges the elements in a way based on these calculated values.

This feature enables you to perform conditional `sorting`

, where elements are ordered according to specific `conditions`

or criteria you specify in the `key`

function, providing flexibility for sorting data based on various factors like `length`

, absolute `value`

, or any other custom `logic`

. Consider below illustration:

For this example, we begin by defining a function named `is_prime(num)`

to determine whether a given number is `prime`

or not. To accomplish this, we utilize a series of `examinations`

. If the number is less than or equal to `1`

, we immediately return `False`

since primes must be greater than `1`

. If the number is precisely `2`

, we return `True`

, as it is a `prime`

number. If the number is even (`divisible by 2`

), we again return `False`

, as no even number (`except 2`

) can be prime. Finally, we employ a loop to check if the number is divisible by any odd integer from 3 up to the square root of the number plus `1`

. If it is divisible by any of these `odd`

numbers, we return `False`

, indicating it’s not `prime`

. Otherwise, we return `True`

, signifying it is a `prime`

number.

Next, we initialize a set called `numbers`

containing a collection of `integers`

. This set includes both `prime`

and `non-prime`

numbers in a random order. Now, we want to sort this `set`

, but with a special condition in mind: we want prime numbers to come first in ascending order, followed by `non-prime`

numbers in ascending order.

To achieve this, we use the `sorted()`

function, specifying a custom `key`

function. This `key`

function takes each number `x`

from the set and constructs a `tuple`

. The first element of the tuple is a `Boolean`

value, `not is_prime(x)`

, which evaluates to `True`

for `non-prime`

numbers and `False`

for prime numbers. The second element of the `tuple`

is the number itself, `x`

. By sorting based on this `tuple`

, we ensure that `prime`

numbers come first, sorted in ascending order, and then `non-prime`

numbers follow, also sorted in ascending order.

Finally, we create a new set called `sorted_set_prime_numbers`

from the sorted list, which removes any `duplicate`

elements. When we print `sorted_set_prime_numbers`

, it will display the sorted unique prime numbers followed by the sorted unique `non-prime`

numbers, achieving the desired result.

As you can observe in the above example, this approach allows you to seamlessly prioritize and `sort`

`prime`

numbers at the beginning of the sorted `list`

, followed by the `non-prime`

numbers, making complex sorting tasks straightforward and highly customizable in Python.

### II. Sorting Dictionaries by Key with sorted()

Sorting dictionaries by key with the `sorted()`

function in Python arranges the dictionary’s `key-value`

pairs based on the keys. This process involves extracting the `key-value`

pairs into a `list`

of `tuples`

using the `items()`

method, sorting those `tuples`

using `sorted()`

, and then converting the sorted `list`

of `tuples`

back into a `dictionary`

.

The result is a `dictionary`

where the keys are organized in `ascending`

order, making it easier to access and manipulate the `dictionary's`

data in a predictable manner. This sorting operation is helpful when you need to work with the `dictionary`

in a specific order based on the `keys`

, such as when you want to iterate through the dictionary or present its contents in an organized fashion. For instance:

In this example, Firstly, we define a class called `SortedDict`

. This class has a constructor method `__init__`

which takes a `dictionary`

, `my_dict`

, as an argument. Inside the `constructor`

, we store this dictionary in an instance variable, `self.my_dict`

, so that it can be accessed throughout the class methods.

Within the `SortedDict`

class, we have a method named `sort_by_keys`

. This method sorts the dictionary stored in `self.my_dict`

by its keys using the `sorted()`

function and returns the sorted dictionary. We create an instance of the `SortedDict`

class, `sorted_dict_instance`

, passing our sample dictionary `my_dict`

as its argument.

We also have a standalone function outside the class, `sort_dict_by_keys`

, which does the same task of sorting a dictionary by its `keys`

. This function accepts a dictionary as an argument and returns the sorted `dictionary`

. Now, we have our sample dictionary `my_dict`

, which contains a mix of `even`

and `odd`

keys paired with corresponding values.

We proceed to use the `SortedDict`

class by creating an instance, `sorted_dict_instance`

, and then calling its `sort_by_keys`

method. This sorts our `my_dict`

by its keys and stores the result in `sorted_result_instance`

. Additionally, we utilize the standalone function `sort_dict_by_keys`

, passing `my_dict`

as its argument, and store the sorted result in `sorted_result_function`

. Finally, we print out both sorted dictionaries, indicating whether we are using the class method or the standalone function.

Using function: {1: ‘one’, 2: ‘two’, 5: ‘five’, 7: ‘seven’, 8: ‘eight’}

By using this approach you can easily sort a dictionary by its keys using both a class and a standalone function.

### III. Handling Exceptions and Errors with sorted()

Handling `exceptions`

and `errors`

with `sorted()`

in Python involves managing situations where the `sorting`

process might encounter `issues`

, such as `incompatible`

data types or missing `keys`

in `dictionaries`

. By addressing these `exceptions`

, you can ensure that your code gracefully handles potential errors during sorting.

This may include catching `TypeError`

instances when trying to sort `uncomparable`

elements, specifying custom sorting criteria using the `key`

parameter, `reversing`

the sorting order with the `reverse`

parameter, or handling missing `keys`

in dictionaries to prevent `KeyError`

exceptions. Efficiently handling these exceptions helps make your code more resilient and robust, ensuring that it functions as intended even when unexpected data or conditions arise during the sorting process. For example:

Here, we have a `list`

called `data`

that contains a mix of different data `types`

, including `integers`

, `strings`

, and a `floating-point`

number. We start by attempting to sort this `data`

list using the `sorted()`

function within a `try`

block. However, things can get tricky because sorting mixed data types can lead to a `TypeError`

due to the incompatibility of certain elements. If such an `exception`

occurs during sorting, we catch it using the `except`

block, where we print an `error`

message indicating the nature of the `TypeError`

.

To address this issue, we take a proactive approach. Inside the `except`

block, we create a new list named `filtered_data`

using a list comprehension. This list comprehension iterates through the elements in the original `data`

list and includes only those that are either `integers`

or `floating-point`

numbers, filtering out `non-comparable`

elements like `strings`

.

Once we’ve filtered the data, we proceed to sort this sanitized `filtered_data`

list using `sorted()`

and assign the sorted result back to `sorted_data`

. This ensures that we are working with comparable `elements`

. Finally, outside the `try`

and `except`

blocks, we print the `sorted_data`

, which now contains the sorted, compatible elements from the original data list.

Sorted data: [1, 3.14, 5]

This code showcases a practical approach to handling exceptions during sorting by filtering out non-comparable elements and successfully obtaining a sorted result.

## Advantages of python sorted()

Here are some advantages of the Python `sorted()`

function that can be quite valuable to understand:

### I. Ease of Use

You can easily sort various iterable data structures like `lists`

, `tuples`

, and dictionaries with `sorted()`

, making it accessible for different use cases.

### II. Readable Code

It makes your code more readable and maintainable compared to implementing sorting algorithms manually.

### III. Stability

Python’s `sorted()`

function is stable, meaning it preserves the relative order of equal elements. This is useful in scenarios where you want to sort by multiple criteria.

## Practical Usage of sorted()

Python `sorted()`

function has a wide range of practical applications. Here are some practical use cases where `sorted()`

can be very helpful:

### I. Custom Sorting

You can employ the key parameter to perform custom sorting based on specific criteria. For instance, sorting a list of dictionaries by a particular key.

### II. Removing Duplicates

By sorting a list and converting it into a set, you can remove duplicate elements, as sets only contain unique values.

### III. Displaying Data

`Python Sorted()`

is handy for presenting data in a more organized and readable manner, such as sorting results in a table.

`Congratulation!`

You’ve now learned Python `sorted()`

function and explored its myriad of practical applications. This built-in function serves as a flexible and convinient tool in your coding arsenal, simplifying the task of `sorting`

iterable objects. It not only eases the `sorting`

process but also provides customization `options`

, allowing you to define specific sorting criteria and even reverse the order easily.

In this Python Helper guide, you’ve gained knowledge and delved into the features and potential of the Python `sorted()`

function. You’ve discovered its applications with `strings`

, `lists`

, and `tuples`

, and beyond that, you’ve explored how it can be used with custom `functions`

, `sets`

, and `dictionaries`

. Additionally, you’ve acquired insights into handling `exceptions`

and `errors`

that may arise when working with the `sorted()`

function in Python.

So, as you continue your coding journey, remember that Python `sorted()`

function is here to streamline your `sorting`

tasks, enhance your code’s readability, and offer flexibility for a wide range of use cases. With this tool at your disposal, you’re well-equipped to tackle sorting challenges and organize data efficiently. Keep coding and exploring the endless possibilities that Python has to offer!