Open In App

Python List sort() Method

Last Updated : 20 Dec, 2025
Comments
Improve
Suggest changes
45 Likes
Like
Report

The sort() method is used to arrange the elements of a list in a specific order, either ascending or descending. It changes the original list directly, so no new list is created. This method works well for sorting numbers or strings.

Let’s sort a list of numbers in ascending order.

Python
a = [4, 1, 3, 2]
a.sort()
print(a)

Output
[1, 2, 3, 4]

Explanation: a.sort() arranges the list elements in increasing order, a is updated with the sorted values.

Syntax

lst.sort(key=None, reverse=False)

Parameters:

  • key (optional): A function used to decide how elements are compared (for example, key=len sorts strings by length).
  • reverse (optional): Controls the sorting order. False (default) sorts in ascending order, True sorts in descending order.

Sorting in Descending Order

By default, sort() arranges elements in ascending order. To sort values from highest to lowest, we use the reverse=True parameter.

Python
b = [5, 2, 9, 1, 5, 6]
b.sort(reverse=True)
print(b)

Output
[9, 6, 5, 5, 2, 1]

Explanation: reverse=True changes the sorting order to descending

Using key Parameter

The key parameter allows sorting based on a custom rule. For example, strings can be sorted by their length instead of alphabetical order.

Python
c = ["apple", "banana", "kiwi", "cherry"]
c.sort(key=len)
print(c)

Output
['kiwi', 'apple', 'banana', 'cherry']

Explanation: key=len tells Python to compare items using their length. Shorter words appear first

Sorting Tuples

When sorting tuples, you can sort based on a specific element inside each tuple.

Python
d = [(1, 3), (2, 2), (3, 1)]
d.sort(key=lambda x: x[1])
print(d)

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

Explanation: x[1] means sorting is done using the second value of each tuple. Tuples with smaller second values come first

Sorting Strings

You can also define custom rules using a lambda function, such as sorting words by their last character.

Python
a = ["apple", "banana", "kiwi", "cherry"]
a.sort(key=lambda x: x[-1])
print(a)

Output
['banana', 'apple', 'kiwi', 'cherry']

Explanation: x[-1] extracts the last character of each string. Sorting is based on that character

Case-Insensitive Sorting

By default, the sort() method is case sensitive, resulting in all capital letters being sorted before lowercase letters. To perform a case insensitive sort, we can use the str.lower function as the key.

Python
b = ["Banana", "apple", "Grape", "pear"]
b.sort(key=str.lower)
print(b)

Output
['apple', 'Banana', 'Grape', 'pear']

Explanation: str.lower converts all values to lowercase for comparison. Original casing is preserved in the output


Explore