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.

Example :

  •   ( 2 , 1, 4 ,3)
    • sorted = ( 1 , 2 , 3 , 4)
sorted in python

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.

Code #1 :

#pyhton program 
#Sorted 

li=[(1,2),(4,5) ,( 3 ,9)]
print(‘sorted list:’,sorted(li))
print(‘ Orginal List :’ ,li)

Output :

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.

Code #2:

#pyhton program 
#Sorted 

L = [[1,2,5], [3,6], [2,1,9], [8,0,0]] 
  
print (“Normal sort :”sorted(L)) 
  
print (“Sort with sum :”sorted(L, key = sum))

Output :

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

Code #3:

#pyhton program 
#Sorted 
# List elements: (Student’s Name, Marks out of 100 , Age)
p_list = [
    (‘A’7018),
    (‘B’8522),
    (‘D’4530),
    (‘C’9922),
    (‘E’3342)
]
def sorting(item):
    # Since highest marks first, least error = most marks
    error = 100 – item[1]
    age = item[2]
    return (error, age)
sorted_list = sorted(p_list, key=sorting)
print(sorted_list)

Output :

[('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.