Python Sorted() Function

Python Sorted() Function

6 mins read601 Views Comment
Updated on Apr 30, 2024 09:16 IST

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.

python sorted function

One of the most common operations performed on data is Sorting – be it ordering the price of the items you’re buying from lowest to highest on that shopping app or arranging the list of email recipients alphabetically.

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

Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

– / –
40 hours
– / –
5 days
– / –
3 days
3 K
3 weeks
– / –
4 days
– / –
20 hours
– / –
2 months
Free
6 weeks

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)
Copy code

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"])
Copy code

Output

sorted function example

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:


 
#List
number_list = [23, 789, 2, 69]
sorted(number_list)
Copy code

Output

2022_07_image-108.jpg

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.

How to Reverse a String in Python
How to Convert a Python List to String?
Variables in Python

Similarly, let’s see how sorted() works with other iterable.

Example 2:


 
#Tuple
number_tuple = (12, 90, -6, 13)
sorted_tuple = sorted(number_tuple)
print("The sorted tuple is: ", sorted_tuple)
#Set
number_set = {3, 3, 9, 12, 24}
sorted_set = sorted(number_set)
print("The sorted set is: ", sorted_set)
#Dictionary
number_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)
Copy code

Output:

2022_07_image-109.jpg

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:


 
#String
number_string = '962345'
my_string = 'Naukri Learning'
sorted_number_string = sorted(number_string)
sorted_string = sorted(my_string)
print(sorted_number_string)
print(sorted_string)
Copy code

Output:

2022_07_image-110.jpg

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:


 
#List
names = ['Harry', 'Ron', 'Hermione', 'draco']
print(sorted(names))
print(sorted(names, reverse=True))
Copy code

Output:

2022_07_image-111.jpg

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.

Python Sets Practice Programs For Beginners
Exception Handling In Python
Python Data Types

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:


 
#List
names = ['Harry', 'Ron', 'Hermione', 'draco']
print(sorted(names))
print(sorted(names, key=str.lower))
Copy code

Output

2022_07_image-112.jpg

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)
Copy code

Output:

2022_07_image-113.jpg
  • 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)
Copy code

Output

2022_07_image-115.jpg

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])
Copy code

Output:

2022_07_image-116.jpg

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.

What are Perfect Squares?
What is a Prime Number?
How to Check if a Python String is a Palindrome

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!!

About the Author

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