The sorted function in Python serves the purpose of arranging a sequence of items in a specified order. This function is versatile and can be utilized to organize a wide range of data structures or intricate objects seamlessly, either in ascending or descending order. By default, the function arranges the elements in ascending order.
The sorted function accepts three parameters and yields a list arranged in ascending order. When applied to a dictionary, it produces a list containing the keys sorted in order. The time complexity associated with the sorted function is O(n logn).
The sorted function does not rearrange the input sequence itself; instead, it generates a new list that is sorted. To sort a sequence in place, you should utilize the sort method instead of the sorted function.
Python Sorted Function Syntax
The format or syntax of the sorted function is outlined as follows:
sorted(iterable, key=None, reverse=False)
Parameters
- iterable: It is the required parameter that represents an iterable.
- key: It is an optional argument that represents a function. The default value is None.
- reverse: It is also an optional Boolean parameter, and the default value is 'False'. One can pass the reverse parameter 'True' to get the sorted list in reverse order.
Return
It produces a fresh list that includes the elements arranged in a sequentially sorted manner.
Different Examples for Python sorted Function
Let's explore a few instances of the sorted function to gain a better understanding of how it operates.
Python sorted Function Example 1 - Sorting string elements
In this illustration, we will be arranging a string object in order to grasp the concept of the sorted function.
# Python sorted() function example - Sorting string elements
str = "logicpractice" # declaring string
# Calling the sorted function
sorted1 = sorted(str) # sorting string
# Displaying result
print("Sorted String Elements:", sorted1)
Output:
Sorted String Elements: ['a', 'a', 'i', 'j', 'n', 'o', 'p', 't', 't', 'v']
Explanation:
In the preceding example, the sorted function arranges each letter in the string "logicpractice" in alphabetical order and provides a list that contains the elements organized in a sorted format.
Python sorted Function Example 2 - Sorting list, tuple, and dictionary elements using sorted function
The sorted function can be utilized to arrange any iterable, such as a list, tuple, or dictionary. Refer to the example provided below.
# Python sorted() function example -
# Sorting a list, tuple, and dictionary
# Creating a list, tuple, and dictionary
li = [2003, 56, 98, 659, 622, 1002, 3652]
tupl = (232, 2500, 3698, 5264, 2578, 21)
dic = {3: 'Three', 4: 'Four', 1: 'One', 2: 'Two'}
# Calling the sorted function
lisorted = sorted(li) # sorting list elements
tupsorted = sorted(tupl) # sorting tuple elements
dicsorted = sorted(dic) # sorting dictionary keys
# Displaying result
print("Sorted List elements:", lisorted)
print("Sorted Tuple Elements:", tupsorted)
print("Sorted Dictionary Keys:", dicsorted)
Output:
Sorted List elements: [56, 98, 622, 659, 1002, 2003, 3652]
Sorted Tuple Elements: [21, 232, 2500, 2578, 3698, 5264]
Sorted Dictionary Keys: [1, 2, 3, 4]
Explanation:
In the preceding illustration, the sorted function organizes the components of both the list and the tuple, yielding distinct sorted lists for each. Regarding the dictionary, it exclusively arranges the keys and provides a list that contains these keys in a sorted order.
Python sorted Function Example 3 - Sorting list elements in reverse order using the sorted function
To arrange the list in descending order (reverse order), provide True as an argument for the reverse parameter. This will result in the list being sorted in reverse sequence.
# Python sorted() function example - Sorting list elements
# in reverse order using sorted function
# Creating a list
li = [2003, 56, 98, 659, 622, 1002, 3652]
# Calling the sorted function
lisorted = sorted(li, reverse=True) # Sorting list in descending order
# Displaying result
print("Sorted list elements:", lisorted)
Output:
Sorted list elements: [3652, 2003, 1002, 659, 622, 98, 56]
Explanation:
In the preceding example, we have supplied True in the reverse parameter, which organizes the list items in reverse or descending sequence and yields a list that comprises the elements arranged in descending order.
Python sorted Function Example 4 - Exploring Key Argument with Lambda Function
The key parameter serves to modify the criteria used for sorting. It accepts a function that generates a key referred to as a comparison key for every element. In this context, the key function processes each element from the iterable, creating a relevant comparison key for that element according to the specified function. The sorted function then utilizes these comparison keys in the sorting procedure.
The default value for the key argument is None. For instance, if you need to arrange a list of strings according to their length, you can provide the 'len' function as an argument for the key parameter.
In this instance, we are organizing a collection of tuples by providing a lambda function as the key argument during the execution of the sorting function. This lambda function computes the total of the elements within each tuple.
# Python sorted() function example -
# Passing a lambda function as a key parameter
# Creating a list of tuples
li = [(2, 15), (3, 5), (65, 5), (8, 5)]
# Calling the sorted function
# Sorting list by getting the sum of elements in the tuple
lisorted = sorted(li, key=lambda x: sum(x))
# Displaying result
print("Sorted list of tuples:", lisorted)
Output:
Sorted list of tuples: [(3, 5), (8, 5), (2, 15), (65, 5)]
Explanation:
In the preceding example, the sorted function arranges the elements (tuples) according to the total of their individual components. The lambda function processes each element (tuple) from the key input and yields the associated sum values to be used as comparison keys. The sorted function then utilizes these keys to order the elements within the list.
Python sorted Function Example 5 - Exploring Key Argument with Simple Function
In this instance, we are providing a sum function in place of a lambda function for the key argument within the same illustration.
# Python sorted() function example -
# Passing a lambda function as a key parameter
# Creating a list
li = [(2, 15), (3, 5), (65, 5), (8, 5)]
# Calling the sorted function
# Sorting list by getting sum of tuples
lisorted = sorted(li, key=sum)
# Displaying result
print("Sorted list of tuples:", lisorted)
Output:
Sorted list of tuples: [(3, 5), (8, 5), (2, 15), (65, 5)]
Explanation:
In Python, the sum function is a built-in feature that computes the total of a collection of values. In the preceding example, the key parameter takes each tuple from the list and supplies it to the sum function. The sum function subsequently yields the total value for each tuple. The sorted function utilizes these total values as a comparison key while executing the sorting operation.
Advantages of the sorted function
Here are some potential advantages of the sorted function below:
- Easy to use: The sorted function is very easy to use. It requires only one mandatory parameter, which is the iterable, and other parameters key and reverse, can be used to customize the sorting.
- Immutability: The sorting function creates a new sorted list leaving the passed sequence unchanged. This feature can be useful when we want sorted data as well as no effects on the original data.
- Customizable Sorting: The key parameter can be used to set the sorting criteria. By using this feature, we can easily customize the sorting process. Also, we can use the reverse parameter to sort the data reverse order.
Applications of the sorted function
Some of the common applications of sorted functions are listed below:
- Data Analysis: The sorted function is frequently utilized where sorted data is required. By using the sorted function, data analysts can easily generate insights.
- Custom Sorting: When we want to sort complex objects, we can use the key features to set the sorting criteria of our specific demand.
- Displaying Results: When we want to display the result in a sorted manner to our users, we can use the sorted function to sort the data.
Conclusion
Utilizing Python's sorted function, we can effortlessly and efficiently arrange various types of data structures. Its adaptability and ease of use allow it to cater to a wide range of sorting scenarios, from straightforward lists and strings to more intricate objects. By leveraging the key parameter, we can tailor the sorting process to our specific requirements. The sorted function in Python offers a reliable and user-friendly approach for organizing data, establishing itself as an essential resource for all programmers.