Video courses for company/skill based Preparation
Purchase mock tests for company/skill building
Sorted() function in Python
Sorted() function in Python :
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 orginal sequence.
- ( 2 , 1, 4 ,3)
- sorted = ( 1 , 2 , 3 , 4)
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.
Code #1 :
sorted list: [(1, 2), (3, 9), (4, 5)]
Orginal List : [(1, 2), (4, 5), (3, 9)]
User Defined Sorting :
- 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.
Normal sort : [[1, 2, 5], [2, 1, 9], [3, 6], [8, 0, 0]]
Sort with sum : [[1, 2, 5], [8, 0, 0], [3, 6], [2, 1, 9]]
In the above Program , the inner list is sorted according to their sum in ascending order as sum of ( 1+ 2 + 3) < ( 3+6) .
Which means that the slists would be sorted based on their sum instead
[('C', 99, 22), ('B', 85, 22), ('A', 70, 18), ('D', 45, 30), ('E', 33, 42)]
P_list is sorted in such a way that the person with higher marks gets the first position in the list.