Open In App
Related Articles

Python List sort() Method

Improve Article
Save Article
Like Article

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

Python List sort() Syntax

To sort the list in Python, we use the sort() function in Python.

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


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

List sort() in Python Examples 

In the example, we will see different examples to apply Python sort() methods.

Example 1: Sort a List of Numbers in Ascending Order

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


numbers = [1, 3, 4, 2]
# Sorting list of Integers in ascending

Output :

[1, 2, 3, 4]

Example 2: Sort a List of Alphabets In Ascending Order

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


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

Output :

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

Example 3: Sort a 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). To do this we need to pass reverse=True, this will sort numbers or the alphabet in descending Order.


# Python program to demonstrate to
# sorting numbers in descending Order
# Creating List of Numbers
numbers = [1, 3, 4, 2]
# Sorting list of Integers in descending

Output :

[4, 3, 2, 1]

Example 4: Sort the list  by key 

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


# 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
# sorts the array in descending according to
# second element
list1.sort(key=sortSecond, reverse=True)

Output :

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

The difference between sort() and sorted() is that the sort list in Python alters the list directly and produces no output, whereas sorted() doesn’t change the list and returns the sorted list.

Last Updated : 15 Sep, 2023
Like Article
Save Article
Similar Reads
Related Tutorials