
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sorted Function in Python
In this tutorial, we are going to learn about the sorted() function in Python.
The function sorted() is used to sort an iterable in ascending or descending order. We can even sort the list of dictionaries based on different keys and values. Let's get most out of the sorted() function.
The sorted() function is not an in-place algorithm like sort method.
Default sorted()
The function sorted() will sort an iterable in ascending order by default. Let's see an example.
Example
# initializing a list numbers = [4, 3, 5, 1, 2] # sorting the numbers sorted_numbers = sorted(numbers) # printing the sorted_numbers print(sorted_numbers)
Output
If you run the above code, then you will get the following result.
[1, 2, 3, 4, 5]
reverse sorted()
We can set a parameter reverse as True to sort the iterable in descending order. Let's see an example.
Example
# initializing a list numbers = [4, 3, 5, 1, 2] # sorting the numbers sorted_numbers = sorted(numbers, reverse=True) # printing the sorted_numbers print(sorted_numbers)
Output
If you run the above code, then you will get the following result.
[5, 4, 3, 2, 1]
key parameter with sorted()
The function sorted() will take another optional parameter called key. The parameter key is to tell the sorted() on which value it has to sort the list.
Let's say we have a list of dictionaries. We have to sort the list of dictionaries based on a certain value. In this case, we pass key as a parameter with a function that returns a specific value on which we have to sort the list of dictionaries.
Example
# initializing a list numbers = [{'a': 5}, {'b': 1, 'a': 1}, {'c': 3, 'a': 3}, {'d': 4, 'a': 4}, {'e' 'a': 2}] # sorting the list of dict based on values sorted_dictionaries = sorted(numbers, key= lambda dictionary: dictionary['a']) # printing the numbers print(sorted_dictionaries)
Output
If you run the above code, then you will get the following result.
[{'b': 1, 'a': 1}, {'e': 2, 'a': 2}, {'c': 3, 'a': 3}, {'d': 4, 'a': 4}, {'a':
Conclusion
If you have any doubts in the tutorial, mention them in the comment section.