Python sorted() function

Published February 17, 2022

Python's sorted() method outputs a sorted list from an iterable object. The iterable object can be a tuple or a list.  This method always outputs a sorted  list or turple  without interfering with the original sequence

Syntax of the sorted()
The sorted() method is written as follows

sorted(iterable, key, reverse)

The sorted() function supports three parameters:
Iterable: An iterable is a sequence or collection that has to be sorted.
Key(optional): A key or basis for sort comparison.
Reverse(optional) : If true, the iterable would be sorted the reverse way, by default, false.


Example
 

a = [1,2,3,4,5,6,7,8]
print("The Returned Sorted List:"),
print(sorted(a))
print("\n After Reverse sort :"),
print(sorted(a, reverse=True))
print("\n Unsorted set :"),
print(a)


Output

The Returned Sorted List:
[1, 2, 3, 4, 5, 6, 7, 8]

 After Reverse sort :
[8, 7, 6, 5, 4, 3, 2, 1]
Unsorted set :
[1, 2, 3, 4, 5, 6, 7, 8]

 

 

Download Source code

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

213 Views