Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Python Sorted Function

Last Updated on November 1, 2023 by Ankit Kochar

The sorted function in Python is a powerful tool for sorting elements within iterable objects, such as lists, tuples, and strings. Sorting is a fundamental operation in programming, and Python sorted function provides a convenient and efficient way to organize data in ascending or descending order. Whether you’re working with numerical data, strings, or custom objects, the Python sorted function allows you to arrange elements according to specific criteria.

In this article, we will explore the Python sorted function comprehensively. We’ll delve into its syntax, parameters, and how to use it for different data types. Additionally, we’ll discuss custom sorting with the key parameter, sorting in reverse order, and sorting lists of complex objects. By the end of this article, you’ll have a solid understanding of how to leverage the sorted() function to efficiently manage and manipulate data in Python.

What is Python Sorted Function?

The Python 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 function 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 in Python

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 versatile tool that simplifies the process of sorting elements within iterable objects. Sorting is a fundamental operation in programming, and Python’s built-in function makes it accessible and efficient.

In this article, we’ve explored the ins and outs of the Python sorted function, from its basic usage for sorting lists to more advanced scenarios involving custom sorting criteria and reverse sorting. We’ve also discussed how to handle various data types and objects effectively.

As you continue to develop Python applications, remember that the sorted function in Python is a valuable resource for organizing data, whether you’re working with numbers, strings, or complex objects. By mastering its usage and understanding the optional parameters, you can write code that efficiently sorts and manages data according to your specific requirements.

FAQs Related to Python Sorted Function

Here are some FAQs related to Python Sorted Function.

1. How does the sorted() function work in Python?
The sorted() function takes an iterable object as input and returns a new sorted list containing the elements in ascending order by default.

2. Can I use the sorted() function to sort elements in descending order?
Yes, you can use the reverse parameter of the sorted() function to sort elements in descending order. Set reverse=True to achieve this.

3. What is the key parameter in the sorted() function used for?
The key parameter allows you to specify a custom sorting criterion. You can provide a function that calculates a value for each element, and the sorted() function uses these values for sorting.

4. Can I sort strings using the sorted() function?
Yes, the sorted() function can be used to sort strings. By default, it arranges strings in lexicographic (dictionary) order.

5. What is the time complexity of the sorted() function in Python?
The time complexity of the sorted() function is O(n * log(n)), where n is the number of elements in the iterable. This is an efficient sorting algorithm that Python uses under the hood.

6. Can I use the sorted() function with custom objects or data types?
Yes, you can use the sorted() function to sort lists of custom objects by specifying a custom sorting key using the key parameter. Ensure that your custom objects have a well-defined comparison method (lt, le, etc.) to enable sorting.

Leave a Reply

Your email address will not be published. Required fields are marked *