sort () in Python

Python Methods and Functions

The sort function can be used to sort the list in ascending or descending order.

Sort the list in ascending order.

Syntax

 List_name.sort () This will sort the given list in ascending order. 

This function can be used to sort a list of integers, floats, strings, and more.

# List of integers

numbers = [ 1 , 3 , 4 , 2 ]

 
# Sort the list of integers
numbers.sort ()

 

print (numbers)

 
# List of numbers from pla decimal point

decimalnumber = [ 2.01 , 2.00 , 3.67 , 3.28 , 1.68 ]

 
# Sort the floating point list
decimalnumber.sort ()

 

print (decimalnumber)

 
# List of strings

words = [ "Geeks" , "For" , "Geeks" ]

  
# Sort the list of strings
words.sort ()

 

print (words)

Output:

 [1, 2, 3, 4] [1.68, 2.0, 2.01, 3.28, 3.67] ['For',' Geeks', 'Geeks'] 

Sort the list in descending order.

Syntax

 list_name.sort (reverse = True) This will sort the given list in descending order. 

# List of integers

numbers = [ 1 , 3 , 4 , 2 ]

 
# Sort a list of integers

numbers.sort (reverse = True )

 

print (numbers)

  
# Floating point list

decimalnumber = [ 2.01 , 2.00 , 3.67 , 3.28 , 1.68 ]

  
# Sort a list of floating point numbers

decimalnumber.sort (reverse = True )

 

print (decimalnumber)

  
# List of strings

words = [ " Geeks " , " For " , "Geeks" ]

 
# Sort the list of strings

words.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 () does not require any additional 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

Returned value:

It returns a sorted list according to the passed parameter .

Exit:

 [(1, 1), (1, 2), (3, 3 )] [(3, 3), (1, 2), (1, 1)] 

Thanks to the striver for contributions to this topic.





# Python program to demonstrate sorting by user
# selection

 
# function to return second element
# two elements are passed as a parameter

def sortSecond (val) :

return val [ 1

  
# list1 to demonstrate the use of sorting
# using the second key

list1 = [( 1 , 2 ), ( 3 , 3 ) , ( 1 , 1 )]

  
# sorts the array in ascending order according to
# second element

list1.sort (key = sortSecond) 

print (list1)

 
# sorts the array in descending order according to
# second element

list1.sort (key = sortSecond, reverse = True )

print (list1)