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.
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
#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.
Login/Signup to comment