In this tutorial, you will learn about the python sorted() function and also you will learn how to use the python built-in sorted function.
In previous tutorials we have seen lots of Python built-in functions along with examples.
Python sorted() function
Python sorted function is a built-in function that is used to sort the specified iterable object. sorted() function sort any sequence (list, tuple, set) and always return a list in a sorted manner, without modifying the original sequence.
You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically.
The syntax of sorted function in Python is:-
sorted(iterable, key = key, reverse = False)
sorted function in Python takes three parameters.
- iterable:- Required. The sequence to sort, list, dictionary, tuple, etc.
- key:- Optional. A Function to execute to decide the order. Default is None.
- reverse:- Optional. A Boolean. False will sort ascending, True will sort descending. Default is False.
Note:- You cannot sort a list that contains both string values and numeric values.
Python sorted function examples
Here we have took various examples to understand python sorted function.
#Sort the list a = [1, 3, 2, 4, 5, 6, 8, 9, 10] b = sorted(a) #Sort the list n ascending order print('Sorted list is:- ', b) #Sort the list n descending order c = sorted(a, reverse = True) print('Reverse sort: ', b) #Original list print('Original list:- ', a)
Sorted list is:- [1, 2, 3, 4, 5, 6, 8, 9, 10] Reverse sort: [1, 2, 3, 4, 5, 6, 8, 9, 10] Original list:- [1, 3, 2, 4, 5, 6, 8, 9, 10]
Sorting in Ascending order
When you want to sort in ascending order then you don’t need to mention the reverse parameter in the sorted function.
a = ["h", "b", "a", "c", "f", "d", "e", "g"] x = sorted(a, reverse = True) print(x)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
Sorting in Descending order
When you want to sort in ascending order then you need to mention the reverse parameter in the sorted function.
a = ("h", "b", "a", "c", "f", "d", "e", "g") x = sorted(a, reverse = True) print(x)
['h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
In this article, you have learned all about Python sorted function along with examples. Python sorted function is the best to function to sort any specified iterable in ascending order or descending order.
If you like this article, please share and keep visiting for further Python built-in functions tutorial.
Python built-in functions
For more information:- Click Here