Sort() Method in Python

Sort in Python : 

Python provide us an in-built function to sort an list is  – sort (). Let’s see about Sort() Method in Python.

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

Example :

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

Learn about sorted() function here

sort in python

Working:

  • sort() function uses TIM SORT 
  •  TIM sort is a hybrid sorting algorithm that is extracted from insertion sort and merge sort
  • Time complexity of TIM sort / Sort() Method in Python is O(n log(n))
  • Implemented by Tim peters in 2002 to use in the Python programming

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:

#python program 
#Sort

li=[(1,2),(4,5) ,( 3 ,9)]
print(‘Before sorting :’ ,li)
#sort acording to the 2nd element of the tuple of the list
li.sort(key=lambda x : x[1],reverse=True
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.