The Python list sort() function is used to sort or arrange all items in an existing list into ascending or descending order. We can use the sort() function on any list with a single data type, including integers, strings, nested lists, a list of tuples, or a list of dictionaries.
By default, the Python list sort() function decides the sorting criteria and modifies the original string. For example, ascending numbers from 0 to 9 and strings from the alphabet a to z. However, we can change the sorting factor using the custom functions.
Python list sort() syntax
The syntax behind the list sort() function to sort the list items is
listName.sort(key = None, reverse = False)
From the above Python list sort() function syntax, the listName is the original list on which we want to perform sorting operations.
Parameters:
- key: It is an optional parameter. It accepts a function name and uses that function to decide the sorting criteria. It performs the comparison (for sorting) based on this function.
- reverse: It is an optional parameter that controls the sorting order. The default value of False means the list items are sorted in ascending order.
Return Value: The Python list sort() function does not return any value. It modifies the original list by arranging the list items in ascending or descending order
The syntax to sort the list items in ascending order is shown below.
# Ascending
listName.sort()
The syntax of the Python sort() function for arranging list items in descending order is shown below.
# Descending or Reverse
listName.sort(reverse = True)
It is the syntax of the sort() with a key parameter. From the below sort() syntax, Function_Name can be any user-defined function or any built-in function, including len, min, max, etc., inside it. For example, key = len will sort the list of strings by their length.
# Using Built-in or User-defined Function listName.sort(key = Function_Name)
Python List sort() function example
As we mentioned earlier, by default, the sort() function arranges the total number of items in a list in ascending order.
To demonstrate the same, we declared an integer list of six elements. Next, we utilized the sort() function without any parameters to perform ascending operations. As we all know, the function won’t return any value, so we used the print() function to display the output.
a = [10, 190, 120, 180, 120, 105]
a.sort()
print(a)
If you observe the output, all list items (integers) are arranged in ascending order (from low to high).
10, 105, 120, 120, 180, 190]
Python list sort() on Positive and Negative Numbers
In the following example, we used a list containing the positive and negative numbers. The sort() function arranges the negative numbers and the positive numbers.
n = [10, -20, 0, 20, -6, 15]
n.sort()
print(n)
[-20, -6, 0, 10, 15, 20]
Sorting floating-point numbers
Similar to integers, we can use the Python list sort() function to sort floating-point numbers. When sorting floating-point numbers, the sort() function considers decimal points.
n = [5.7, 5.2, 5.5, 6.7, 5.75, 5.45]
n.sort()
print(n)
[5.2, 5.45, 5.5, 5.7, 5.75, 6.7]
Python list sort in descending order
As we all know, the default value of the reverse argument is False. We set that one argument to True (reverse = True), which allows us to organize the items in descending order. The following code sorts the four integer list elements in descending or reverse order.
a = [10, 40, 70, 20]
a.sort(reverse=True)
print(a)
As you can see from the list below, the list items are arranged from the highest value to the lowest (descending).
[70, 40, 20, 10]
We used the code below to give a clear picture of the difference in output with reverse argument values, True or False. Here, we used the same integer list and applied the Python list sort() function without an argument for ascending, and used the reverse parameter value True for descending order.
n1 = [13, 98, 125, 191, 22, 9, 91, 78, 242]
n1.sort()
print("Ascending = ", n1)
n2 = [13, 98, 125, 191, 22, 9, 91, 78, 242]
n2.sort(reverse = True)
print("Descending = ", n2)
Compare the result of the ascending and descending ordered list items.
Ascending = [9, 13, 22, 78, 91, 98, 125, 191, 242]
Descending = [242, 191, 125, 98, 91, 78, 22, 13, 9]
TIP: Please refer to the List article and the List functions article in Python to understand everything about them. And also, refer to the len, min, and max.
Python sort list of dynamic Integers
This program is the same as the first example. However, this time we are allowing the user to enter the list length. Next, we used a for Loop and the append function to add numbers to the empty list. Lastly, we used the sort() function to sort the integer list in ascending order.
intLi = []
number = int(input("Please enter the Total Number of Elements: "))
for i in range(1, number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
intLi.append(value)
print("Before is : ", intLi)
intLi.sort()
print("Items After applying is : ", intLi)

In the above program, if we use the reverse argument and set it to True, the sort() function arranges the list elements in descending order. To do so, replace the line below
intLi.sort()
with the below-mentioned line
intLi.sort(reverse = True)
Result
Items After applying is : [22, 9, 8, 7]
Python list sort() function on string items
In our previous examples, we utilized the sort() function to arrange the numeric values in ascending or descending order based on their value. Apart from that, we can use the list sort() function on strings to arrange them in alphabetical order from ‘a’ to ‘z’ or ‘z’ to ‘a’ (reverse).
This section demonstrates how to sort the string list items (text elements) in ascending and descending order. In this example, we declared a list of six strings (words). Next, we used the list sort() function to sort them in ascending order. As we used the method without any parameter, it uses alphabetical order to arrange the string items from A to Z.
Fruit = ['Orange', 'Banana', 'Watermelon', 'Kiwi', 'Grape', 'Blackberry']
Fruit.sort()
print(Fruit)
['Banana', 'Blackberry', 'Grape', 'Kiwi', 'Orange', 'Watermelon']
Python sort list of strings in descending order
Similarly, we can use the reverse argument to arrange the string words in descending order. In this example, we used the reverse = True option inside the sort() function. It means this example returns the reverse order of the above example.
fruits = ['orange', 'banana', 'apple', 'kiwi', 'grape']
fruits.sort()
print("\nAscending = ", fruits)
# Descending Order
fruits.sort(reverse = True)
print("Descending = ", fruits)
Ascending = ['apple', 'banana', 'grape', 'kiwi', 'orange']
Descending = ['orange', 'kiwi', 'grape', 'banana', 'apple']
How to sort the user-entered string list of words?
This example allows users to enter their own strings or words and add them to an empty list. Next, we used the Python list sort() function to arrange the user-inserted strings in ascending order.
strSL = []
number = int(input("Please enter the Total Number of Elements: "))
for i in range(1, number + 1):
item = input(" %d Element : " %i)
strSL.append(item)
strSL.sort()
print(strSL)
Please enter the Total Number of Elements: 4
1 Element : kiwi
2 Element : dragon
3 Element : apple
4 Element : banana
['apple', 'banana', 'dragon', 'kiwi']
Sorting the user-entered string list in reverse order
In this program, we used the reverse argument inside a function to sort the string items in descending. Next, we used the key = len to sort the list items in ascending and descending order using string length.
str1 = []
number = int(input("Please enter the Total Elements: "))
for i in range(1, number + 1):
item = input("%d Element : " %i)
str1.append(item)
str1.sort(reverse = True)
print("Descending : ", str1)
str1.sort(reverse = True, key = len)
print("Length : ", str1)
Please enter the Total Elements: 5
1 Element : cherry
2 Element : apple
3 Element : orange
4 Element : kiwi
5 Element : blackberry
Descending : ['orange', 'kiwi', 'cherry', 'blackberry', 'apple']
Length : ['blackberry', 'orange', 'cherry', 'apple', 'kiwi']
Python list sort() function on text
In the following example, the custom function uses the last index position. It means when we call this function as the key parameter value, the sort() function uses the last character in each string as the sorting factor. If you observe the output, the list of strings is arranged based on the last character in each word.
def lastChar(txt):
return txt[-1]
fruits = ['orange', 'berry', 'apple', 'kiwi']
fruits.sort(key = lastChar)
print(fruits)
['orange', 'apple', 'kiwi', 'berry']
Case sensitivity of the Python list sort() function
By default, the list sort() function is case sensitive, meaning uppercase and lowercase characters are treated differently. When you apply the sort() function on the same word with upper and lower cases, the uppercase letters come first because the ASCII codes of uppercase letters are smaller compared to the lowercase.
In the example below, the sort() function arranged the fruits in ascending order. Here, Apple comes first, followed by Blackberry and an apple. Here, the ASCII value of A is the smallest, and the next smallest is the ASCII value of B. When Apple and apple are compared, the ASCII value of A is smaller than that of a.
fruits = ['apple', 'oranges', 'Blackberry', 'kiwi', 'Apple']
fruits.sort()
print(fruits)
['Apple', 'Blackberry', 'apple', 'kiwi', 'oranges']
TIP: Use the string lower() and upper() functions to convert all string words in the list to either lowercase or uppercase. Next, apply the sort() function.
Sorting strings by numbers inside them
There are situations where we might have to sort the strings based on the numeric values in them. For instance, sorting the file names or products where the item ends with a number. In such a case, we must be careful because by default, the Python list sort() function sorts string alphabetical order.
The following example uses a combination of the same string, all items, and each string ends with a different number. If you use the regular sort() function, it will consider 10 before 2 because it checks 1 (from 10) against 2, so 10 comes first.
products = ["Bike4", "Bike10", "Bike2", "Bike1"]
products.sort()
print(products)
['Bike1', 'Bike10', 'Bike2', 'Bike4']
To resolve this, we can use the lambda expression. Here, it will sort the bikes in descending order based on the ending numbers.
products = ["Bike4", "Bike10", "Bike2", "Bike1"]
products.sort(key = lambda x: int(x.replace("Bike", "")),
reverse = True)
print(products)
['Bike10', 'Bike4', 'Bike2', 'Bike1']
Sorting the string dates
If the given dates are in the string format, we can use the Python list sort() function with a lambda expression to sort dates in ascending or descending order. Here, the strptime() function parses the string representation of dates into a date object. Next, the sort() function sorts dates without any issue.
from datetime import datetime
dates = ["15-04-2026", "10-06-2026", "31-12-2025"]
dates.sort(key=lambda d: datetime.strptime(d, "%d-%m-%Y"))
print(dates)
['31-12-2025', '15-04-2026', '10-06-2026']
Python list sort using key argument & custom function
As we mentioned earlier, the list sort() function has another argument called a key. It accepts any built-in method or custom user-defined function to determine the sorting factor. In this example, we created a user-defined function length. It finds the length of a given string.
Next, we are using this function as the key value. It means fruits are organized based on their length in ascending. In the next line, we used the reverse parameter, along with this key argument. It orders the fruits based on the length of each string word in descending.
def length(str):
return len(str)
fruits = ['apple', 'oranges', 'blackberry', 'kiwi', 'cherry']
fruits.sort(key = length)
print("Asc = ", fruits)
fruits.sort(reverse = True, key = length)
print("Desc = ", fruits)
Asc = ['kiwi', 'apple', 'cherry', 'oranges', 'blackberry']
Desc = ['blackberry', 'oranges', 'cherry', 'apple', 'kiwi']
To use the key argument, you don’t have to create a custom function. It allows you to use any built-in functions.
key argument and built-in len function
The Python list sort method example is the same as the above. However, we are using the built-in common len function.
As we all know, the len() function returns the total number of characters in a string. Here, key = len means the sort() function finds the length of each string (word) in a list and compares its length. The lower the length, place that element as the first list item, and arrange the remaining string words based on their length.
It means the first one organizes the list based on word length in ascending order, and the second one in descending order using their length.
fruits = ['oranges', 'blackberry', 'apple', 'kiwi', 'cherry']
fruits.sort(key = len)
print("\nAscending = ", fruits)
fruits.sort(reverse = True, key = len)
print("Descending= ", fruits)
Ascending = ['kiwi', 'apple', 'cherry', 'oranges', 'blackberry']
Descending= ['blackberry', 'oranges', 'cherry', 'apple', 'kiwi']
Python list sort() function with Key parameter on integers
In the example below, we defined a custom function that returns the absolute positive value of a given number. Next, the sort() function uses this absolute function as the key parameter value. The sort() function arranges the list items considering all numbers as positive integers. It means while arranging the list items in ascending order, -20, -40, and -60 are treated as 20, 40, and 60.
def absolute(n):
return abs(n)
a = [-60, 10, -40, 30, -20, 50]
a.sort(key = absolute)
print(a)
[10, -20, 30, -40, 50, -60]
Python list sort() function with a lambda expression
We have already explained the key parameter advantages in the previous section. We have defined a function that considers or changes the default sorting factor.
The lambda expression does the same. However, instead of defining a new function for the small task, we can write the expression. For example, the following is a shorter way of sorting a list of strings in ascending order.
fruits = ['apple', 'oranges', 'blackberry', 'kiwi',]
fruits.sort(key = lambda x: len(x))
print(fruits)
['kiwi', 'apple', 'oranges', 'blackberry']
Python list sort() function on Nested Items
Similar to the regular lists, we can use the sort() function to arrange the nested lists in ascending or descending order. However, the key argument plays a vital role.
The following examples help you understand the sort() function on nested list items. Here, we declared a list of lists and utilized the sort() function on it. By default, the sort() function considers the first value in each sub-list as the sorting factor and arranges the nested lists based on it.
In the case below, the Python sort() function considers the first items in each nested list (71, 222, 14, and 99) to arrange the lists. As we used the sort() method without any parameter, they should be arranged in ascending order, and it will be 14, 71, 99, and 222. So, the final result is [[14, 15], [71, 222], [99, 77], [222, 13]].
n = [[71, 222], [222, 13], [14, 15], [99, 77]]
n.sort()
print(n)
[[14, 15], [71, 222], [99, 77], [222, 13]]
Python sort nested list items using user defined function
You don’t have to restrict yourself to sorting the nested list with the first value. By creating a user-defined function, you can use any value to order the nested items.
In this example, we created a function to select the second value as the key for arranging list items. It means the first code snippet uses a custom function that takes the second item ((222, 13, 151, and 77) in a nested list as the sorting factor.
So, it arranges the list items in ascending order based on the second item of each nested list. The next section sorts the list items based on the second item in descending order.
def second(value):
return value[1]
n1 = [[17, 222], [222, 13], [14, 151], [99, 77]]
n1.sort(key = second)
print("\nAscending =", n1)
n2 = [[17, 222], [222, 13], [14, 151], [99, 77]]
n2.sort(reverse = True, key = second)
print("Descending =", n2)
Ascending = [[222, 13], [99, 77], [14, 151], [17, 222]]
Descending = [[17, 222], [14, 151], [99, 77], [222, 13]]
Python sort nested List items in descending using key and reverse
We have taken another example to explain this key argument and custom functions. This time also used the second value as the key. As you can see, though, we have three values in a nested list, and the sort() function was sorting the items by the second item.
def second(value):
return value[1]
n = [[17, 222, 15], [222, 13, 55], [14, 151, 31], [99, 77, 9]]
n.sort(key = second)
print("\nAscending = ", n)
# Descending Ordern.sort(reverse = True, key = second)
print("Descending = ", n)
Ascending = [[222, 13, 55], [99, 77, 9], [14, 151, 31], [17, 222, 15]]
Descending = [[17, 222, 15], [14, 151, 31], [99, 77, 9], [222, 13, 55]]
Let me change this key value to 3 nested values. We can do this by changing the item index position to 2 in a user-defined function. It means the sort() function considers the third item in each nested list as the sorting factor. Here, 15, 55, 31, and 9 are considered sorting factors to arrange the nested lists in ascending and descending order.
def third(value):
return value[2]
n = [[17, 222, 15], [222, 13, 55], [14, 151, 31], [99, 77, 9]]
n.sort(key = third)
print("\nAscending = ", n)
n.sort(reverse = True, key = third)
print("Descending = ", n)
Ascending = [[99, 77, 9], [17, 222, 15], [14, 151, 31], [222, 13, 55]]
Descending = [[222, 13, 55], [14, 151, 31], [17, 222, 15], [99, 77, 9]]
Difference between sort(reverse = True) vs reverse() function
By default, the Python list sort() function with the reverse parameter set to True arranges the list of items in descending order. On the other hand, the built-in reverse() function reverses all items in a list. However, if we use the reverse() function after applying the normal sort() function with any argument, the result is the same.
In the example below, we use two integer lists with the same five items to compare the output. First, the sort() function will arrange the list items in ascending order. Next, the reverse() function reverses those list items.
In the second section, we used the sort() function with a reverse argument, which will arrange list items in descending order.
n1 = [11, 99, 44, 9, 55]
n1.sort()
n1.reverse()
print(n1)
n2 = [11, 99, 44, 9, 55]
n2.sort(reverse=True)
print(n2)
[99, 55, 44, 11, 9]
[99, 55, 44, 11, 9]
Sorting a list of tuples
Similar to the nested lists, the Python list sort() function considers the first value in each nested tuple as the sorting factor. In the example below, we use the lambda expression to sort the list of tuples in ascending order based on the second item in each tuple.
n = [(12, 20), (9, 55), (14, 40)]
n.sort(key=lambda x: x[1])
print(n)
[(12, 20), (14, 40), (9, 55)]
Sorting a list of dictionaries
Apart from the regular lists, we can use the Python sort() function to sort a list of dictionaries. In the example below, we declared a list of four dictionary items consists of student names and their marks.
Within the sort() function, we used a lambda expression to sort the list of dictionary items based on student marks.
students = [
{"name": "John", "marks": 87},
{"name": "Tracy", "marks": 89},
{"name": "Mike", "marks": 94},
{"name": "Charlie", "marks": 78}
]
students.sort(key=lambda s: s["marks"])
print(students)
[{'name': 'Charlie', 'marks': 78},
{'name': 'John', 'marks': 87},
{'name': 'Tracy', 'marks': 89},
{'name': 'Mike', 'marks': 94}]
To sort the dictionary items based on the student names, replace the line below w
students.sort(key=lambda s: s["marks"])
With the following line
students.sort(key=lambda s: s["name"])
Sorting by Multiple Keys
In all our previous examples, we used one item as the sorting factor to arrange the list of lists or tuple items. However, with the Python list sort() function and the lambda expression, we can use multiple keys as the sorting factor.
In the example below, there is a list of nested tuples, each of which has three items: student name, age, and their marks. In the sort() function, we used n[0], n[2], which means, first, it sorts the student by their name and then by their marks.
students = [("John", 25, 87), ("Tracy", 32, 89),
("Mike",29, 94), ("Charlie", 27, 78)
]
students.sort(key=lambda n: (n[0], n[2]))
print(students)
[('Charlie', 27, 78), ('John', 25, 87), ('Mike', 29, 94), ('Tracy', 32, 89)]
sort() vs sorted()
The Python list sort() function arranges the list items in ascending or descending order in place, meaning it modifies the original list. On the other hand, the sorted() function preserves the original and assigns the sorted list to a new one. Please refer to the sorted() article for a deeper understanding of the differences.
From the output of the example below, you can see that the sorted() function did not change the original list items. Instead, it assigned the list items in ascending order to a new list.
n = [400, 500, 200, 600]
a = sorted(n)
print(a)
print(n)
[200, 400, 500, 600]
[400, 500, 200, 600]
How to sort mixed List items?
To sort the list items, the Python list sort() function must compare each item against the other list elements. However, when a list contains mixed data types, the sort() function can’t compare strings and integers, and it raises a TypeError. So, make sure a list consists of a single data type. Otherwise, define a function to make a common value for the comparison using the key argument.
MixedLi = ['apple', 1, 5, 'Kiwi', 'Mango']
MixedLi.sort()
print(MixedLi)
It is throwing an error because it can’t apply < operation on a string and an int.
Traceback (most recent call last):
TypeError: '<' not supported between instances of 'int' and 'str'