Python Sorted() Function
The sorted() function is designed to return a new sorted list from the items in an iterable. Whether you're dealing with numbers, strings, or custom objects, sorted() can handle it all. Unlike the list.sort() method, which sorts a list in place, sorted() works with any iterable and always returns a new list. In this article, we will explore sorted functions in Python with the help of examples.
As a programmer, too, you will be working with data where you’d need to perform sorting at some point. In Python, a robust in-built method called sorted() offers this functionality. We will be learning more about the workings of this method in this article. So, without further ado, let’s get started!
Table of Content
Best-suited Python courses for you
Learn Python with these high-rated online courses
Python Sorted() Function Syntax
The sorted function in Python is a built-in function used to sort elements in an iterable (like a list, tuple, string, etc.) in a specific order. It returns a new list containing the elements in the sorted order without modifying the original iterable.
- sorted takes an iterable as input and returns a new list containing the elements of the original iterable in sorted order.
- By default, it sorts elements in ascending order, meaning from lowest to highest.
Syntax of Sorted Function
sorted(iterable, key=None, reverse=False)
Parameters:
- Iterable: input data (a list, tuple, string, or dictionary) you want to sort.
- Key: used to extract a comparison key from each element in the interable. It is an optional value.
- Reverse: This is a boolean value. If set to TRUE, the sort list is reversed (or sorted in descending order). By default, it is set to False, i.e., it will return in ascending order.
Now, let’s have an example to understand better how to use sorted functions in Python.
# Sort a list of custom objects using a key function:books = [ {"title": "The Lord of the Rings", "author": "J.R.R. Tolkien"}, {"title": "Pride and Prejudice", "author": "Jane Austen"}, {"title": "The Great Gatsby", "author": "F. Scott Fitzgerald"},]sorted_books = sorted(books, key=lambda book: book["title"])
Output
In the above example, the sorted function will sort the title of the books alphabetically.
Must Read: What is Python?
Must Check: Python Online Course and Certifications
How does the Sorted() Method Work?
Using simple sorted() function:
Let’s see how the sorted() method works with only the mandatory argument, i.e., the iterable object:
Example 1:
#Listnumber_list = [23, 789, 2, 69]sorted(number_list)
Output
What have we done here?
As you can see from the code above, we defined a list with 4 numerical-valued items.
Then, we simply applied the sorted() function to the given list. The function returned an ordered list sorted in ascending order as the output.
Similarly, let’s see how sorted() works with other iterable.
Example 2:
#Tuplenumber_tuple = (12, 90, -6, 13)
sorted_tuple = sorted(number_tuple)
print("The sorted tuple is: ", sorted_tuple)
#Setnumber_set = {3, 3, 9, 12, 24}
sorted_set = sorted(number_set)
print("The sorted set is: ", sorted_set)
#Dictionarynumber_dict = {'q': 1, 'w': 2, 'e': 3, 'r': 4, 't': 5, 'y': 6}
sorted_dict = sorted(number_dict)
print("The sorted dictionary is: ", sorted_dict)
Output:
What have we done here?
As you can see from the code above, we defined a tuple, a set, and a dictionary with 4, 5, and 6 numerical-valued items, respectively.
Then, we applied the sorted() function to all three iterable objects. The output displays a list sorted in ascending order. The dictionary is sorted based on the ASCII code of each key in the key-value pair.
Note that even though the inputs were not a list object, the sorted() method always returns a new list. You can later convert the returned object into the type of your choice through type casting in Python.
Now, let’s see how sorted() works with strings.
Example 3:
#Stringnumber_string = '962345'my_string = 'Naukri Learning'
sorted_number_string = sorted(number_string)sorted_string = sorted(my_string)
print(sorted_number_string)print(sorted_string)
Output:
What have we done here?
In the above code, we defined two strings – a string with numbers as characters and a text string.
Then, we applied the sorted() function to both the string objects. The function treats the str type as a list of items. Each character of the string is considered to be an item of the list object. Hence, each character is sorted based on its ASCII code. So,
- For the number string, the function returns a list of items (string characters) sorted in ascending order.
- For the second string, the function returns a list of items (string characters) sorted in ascending ASCII code order, including the blank space.
Using sorted() with the reverse argument:
Let’s see how the sorted() method works when we specify the reverse parameter:
Example 4:
#Listnames = ['Harry', 'Ron', 'Hermione', 'draco']print(sorted(names))print(sorted(names, reverse=True))
Output:
The list of names given above gets sorted by the first letter of each item string. But this time, we also specify the reverse parameter as True, which outputs a list with the reversed (descending) order of item-strings.
Also, note that the ASCII code for R in ‘Ron’ is lower than small d in ‘draco’ hence, the order. This tells us that while sorting, the casing of the characters is also taken into consideration.
Using sorted() with the key argument:
The key parameter is one of the most powerful components of the sorted() method. This argument expects a function to be passed to it, which will be iterated over each item of the given iterable to determine the resulting order.
Let’s demonstrate this through the following example:
Example 5:
#Listnames = ['Harry', 'Ron', 'Hermione', 'draco']print(sorted(names))print(sorted(names, key=str.lower))
Output
The list of names given above gets sorted by the first letter of each item string. But this time, we also specify the key parameter with the str.lower() function. So, the sorted() method would return a list considering that the first letters of each item-string are in lowercase.
Hence, in the output, we see the list sorted in ascending ASCII code order or the lowercase first letters, i.e., d, h, h, and r.
However, please remember that the method will not alter the original list items in any way.
Limitations of using the key argument:
- The function specified by the key parameter always takes only one argument.
So, if we specify the add() function, for example, it will throw a Type Error because add() requires two arguments:
def add(x, y): return x + y
my_list = [1, 2, 3, 4]sorted(my_list, key=add)
Output:
- The key parameter must be able to handle all the values of the iterable.
For example, let’s say you have a list of numbers represented as strings. When you apply the sorted() method to it, the key parameter attempts to convert them to numbers using int. If a value in the iterable can’t be cast to an integer, then the function fails and throws a Value Error.
my_list = [1, 2, 3, 'four']sorted(my_list, key=int)
Output
Using the lambda function with the key argument:
The key parameter is extremely powerful because it can use almost any function, in-built or user-defined, can be used to manipulate the order of the output.
When working with a user-defined function, instead of writing a standalone function, we can use a lambda function that is defined inline. Consider the following example:
my_list = ['apple', 'Banana', 'Grapes', 'mango', 'cherry']sorted(my_list, key=lambda x: x[::-1])
Output:
What have we done here?
The lambda function calls x[::-1] on each element to reverse a string, and the sorting order is based on the first characters of the reversed strings.
Conclusion
In the above article, we have briefly discussed how sorted functions work in Python with the help of examples. Hope you will like the article.
Keep Learning!!
Keep Sharing!!
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio