sort() in Python
Like C++ sort(), Java sort() and other languages, python also provides built in function to sort. The sort function can be used to sort the list in both ascending and descending order. To sort the list in ascending order. Its time complexity is O(NlogN).
Syntax
# This will sort the given list in ascending order. # It returns a sorted list according to the passed parameter. List_name.sort()
This function can be used to sort list of integers, floating point number, string and others.
Python3
# List of Integersnumbers = [1, 3, 4, 2]# Sorting list of Integersnumbers.sort()print(numbers)# List of Floating point numbersdecimalnumber = [2.01, 2.00, 3.67, 3.28, 1.68]# Sorting list of Floating point numbersdecimalnumber.sort()print(decimalnumber)# List of stringswords = ["Geeks", "For", "Geeks"]# Sorting list of stringswords.sort()print(words) |
Output:
[1, 2, 3, 4] [1.68, 2.0, 2.01, 3.28, 3.67] ['For', 'Geeks', 'Geeks']
To sort the list in descending order.
Syntax
list_name.sort(reverse=True) This will sort the given list in descending order.
Python3
# List of Integersnumbers = [1, 3, 4, 2]# Sorting list of Integersnumbers.sort(reverse=True)print(numbers)# List of Floating point numbersdecimalnumber = [2.01, 2.00, 3.67, 3.28, 1.68]# Sorting list of Floating point numbersdecimalnumber.sort(reverse=True)print(decimalnumber)# List of stringswords = ["Geeks", "For", "Geeks"]# Sorting list of stringswords.sort(reverse=True)print(words) |
Output:
[4, 3, 2, 1] [3.67, 3.28, 2.01, 2.0, 1.68] ['Geeks', 'Geeks', 'For']
Syntax :
list_name.sort() – it sorts in ascending order list_name.sort(reverse=True) – it sorts in descending order list_name.sort(key=…, reverse=…) – it sorts according to user’s choice
Parameters: By default, sort() doesn’t require any extra parameters. However, it has two optional parameters:
reverse – If true, the list is sorted in descending order key – function that serves as a key for the sort comparison
Python
# Python program to demonstrate sorting by user's# choice# function to return the second element of the# two elements passed as the parameterdef sortSecond(val): return val[1]# list1 to demonstrate the use of sorting# using second keylist1 = [(1,2),(3,3),(1,1)]# sorts the array in ascending according to# second elementlist1.sort(key=sortSecond)print(list1)# sorts the array in descending according to# second elementlist1.sort(key=sortSecond,reverse=True)print(list1) |
Output:
[(1, 1), (1, 2), (3, 3)] [(3, 3), (1, 2), (1, 1)]
Please refer Python Sort articles for more Python Sorting articles. Thanks to striver for inputs on this topic.



Please Login to comment...