Skip to content
Related Articles

Related Articles

Python List sort() method

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 16 Aug, 2022
View Discussion
Improve Article
Save Article

Python list sort() function can be used to sort a List in ascending, descending, or user-defined order. In each case, the time complexity is O(nlogn) in Python.

Syntax of sort() function

Syntax: List_name.sort(reverse=True/False, key=myFunc)

Parameter:

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

Example 1: Sort the List of numbers in Ascending Order

The sort() method by default sort element in ascending order as we can see below example:

Python3




# Python program to demonestrate to
# sorting numbers in Ascending Order
  
numbers = [1, 3, 4, 2]
# Sorting list of Integers in ascending
numbers.sort()
print(numbers)

Output:

[1, 2, 3, 4]

Example 2: Sort the List of alphabets in Ascending Order

The sort() method sorts the list in order from A-Z, to a-z in the alphabet. 

Python3




# Sorting List in Descending Order 
# Creating List
strs = ["geeks", "code", "ide", "practice"]
  
# Sorting list of Integers in ascending
# using sort() methods
strs.sort()
print(strs)

Output:

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

Example 3: Sort the List in Descending Order 

Here, we are sorting the list of numbers in Descending order, the same will be for alphabets(Z-A, z-a).

Python3




# Python program to demonestrate to
# sorting numbers in descending Order
# Creating List of Numbers
numbers = [1, 3, 4, 2]
  
# Sorting list of Integers in descending
numbers.sort(reverse = True)
  
print(numbers)

Output:

[4, 3, 2, 1]

Example 4: Sorting using User-defined Order 

In this example, we are sorting elements using the function based by passing the function to the key parameter of the sort() function.

Python3




# 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  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 :

Start Your Coding Journey Now!