Sorted() is an in-built function in python , which used to sort any type of sequence like list , tuple.
Set is already sorted we need not to sort a set. Sorted sort any type of sequence and returns the sequence in sorted manner without changing the original sequence.
sorted() in Python
The sorted() function is a way to sort a list without using sort() function.
Example :
( 2 , 1, 4 ,3)
sorted = ( 1 , 2 , 3 , 4)
Syntax :
sorted( iterable , key , reverse )
Parameters : sorted takes three parameters from which two are optional.
Iterable : sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any other iterator that needs to be sorted.
Key(optional) : A function that would server as a key or a basis of sort comparison.
Reverse(optional) : If set true, then the iterable would be sorted in reverse (descending) order, by default it is set as false.
sorted() function has an optional parameter called ‘key’ which takes a function as its value. This key function transforms each element before sorting, it takes the value and returns 1 value which is then used within sort instead of the original value.
Login/Signup to comment