Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Sort () in Python

Sort in Python : 

Python provide us an in-built function to sort an list is  – sort ().

Sort is used to arrange the elements of an list in ascending , decesnding or user defined order. The time complexity of the sort funcion is O( nlogn ) where n is number of element in list.

Example :

  • li=[ 2 ,1, 4, 3]
    • sort li – [1, 2, 3, 4]
sort in python

Syntax :

  list_name . sort()

  It will arrange the elements in asscending order.

Code #1:

#pyhton program 
#Sort

li=[3,5,4,1]
print(‘Before sorting :’ ,li)
li.sort()
print(‘After sorting :’ , li)
        

Output :

Before sorting : [3, 5, 4, 1]
After sorting : [1, 3, 4, 5]

Syntax :

  list_name.sort(reverse=True)

  Sort in decreasing order

Code #2:

#pyhton program 
#Sort

li=[3,5,4,1]
print(‘Before sorting :’ ,li)
li.sort(reverse=True)
print(‘After sorting in descending order:’ , li)
        

Output :

Before sorting : [3, 5, 4, 1]
After sorting in descending order: [5, 4, 3, 1]

Syntax :

  list_name.sort(key=…, reverse=…) – it sorts according to user’s choice

Code #3:

#pyhton program 
#Sort

li=[(1,2),(4,5) ,( 3 ,9)]
print(‘Before sorting :’ ,li)
li.sort(key=lambda x : x[1],reverse=True)   #sort acording to the 2nd element of the tuple of the list
print(‘After sorting in descending order:’ , li)
        
b=‘PrepInsta’
b=list(b)
b.sort()
##we can sort an string 
print(b)

Output :

Before sorting : [(1, 2), (4, 5), (3, 9)]
After sorting in descending order: [(3, 9), (4, 5), (1, 2)]
['I', 'P', 'a', 'e', 'n', 'p', 'r', 's', 't']

Note :- String is sorted according to their ASCII value.