Skip to content
Related Articles

Related Articles

Improve Article

Python List sort() method

  • Difficulty Level : Easy
  • Last Updated : 03 Aug, 2021

Python list sort() function can be used to sort a List in ascending, descending, or user-defined order. 

To Sort the List in Ascending Order

Syntax:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

List_name.sort() 



This will sort the given list in ascending order. This function can be used to sort a list of integers, floating-point numbers, strings, and others.

Example 1: Sort the List in Ascending Order

Python3




numbers = [1, 3, 4, 2]
  
# Sorting list of Integers in ascending
numbers.sort()
  
print(numbers)

Output:

[1, 2, 3, 4]

Example 1.1

Python3




strs = ["geeks", "code", "ide", "practice"]
  
# Sorting list of Integers in ascending
strs.sort()
  
print(strs)

Output:

['code', 'geeks', 'ide', 'practice']

To Sort the List in Descending Order 
 

Syntax:

list_name.sort(reverse=True) 

This will sort the given list in descending order.

Example 2: Sort the List in Descending Order 

Python3




numbers = [1, 3, 4, 2]
  
# Sorting list of Integers in descending
numbers.sort(reverse = True)
  
print(numbers)

Output:

[4, 3, 2, 1]

Sorting Using User-defined Order 

Syntax:

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

Parameters:

  • reverse: reverse=True will sort the list descending. Default is reverse=False
  • key: A function to specify the sorting criteria(s)

Example 3: Sorting Using User-defined Order 

Python




# Python program to demonstrate sorting by user's
# choice
  
# function to return the second element of the
# two elements passed as the parameter
def sortSecond(val):
    return val[1
  
# list1 to demonstrate the use of sorting 
# using using second key 
list1 = [(1, 2), (3, 3), (1, 1)]
  
# sorts the array in ascending according to 
# second element
list1.sort(key = sortSecond) 
print(list1)
  
# sorts the array in descending according to
# second element
list1.sort(key = sortSecond, reverse = True)
print(list1)

Output:

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



My Personal Notes arrow_drop_up
Recommended Articles
Page :