Python List sort Function

How to use this Python List sort function with practical examples? This Python List function is used to sort given elements in ascending order, and the syntax behind this is

# Ascending
liName.sort()

# Descending or Reverse
liName.sort(reverse = True)

# Using Built-in or User defined Function
liName.sort(key = Function_Name)

Within this Python list sort function syntax, Function_Name can be any user-defined function. Or you can use any built-in function like len, min, max, etc., inside it.

Python List sort method

The following Python examples show you how to sort integer list items in ascending and Descending order.

In this example, we declared an integer list, and the function sorts the given one in ascending.

a = [10, 190, 120, 180, 120, 105]

a.sort()

print(a)
10, 105, 120, 120, 180, 190]

It has one argument called reverse = True, which allows us to organize the items in descending order. The following code sorts the integer elements in Descending or reverse order.

TIP: Please refer to the List article and methods article in Python to understand everything about them. And also, refer to len, min, and max.

lexm = [13, 98, 125, 191, 22, 9, 91, 78, 242]
print("\n Original = ", exm)

exm.sort()
print("Ascending = ", exm)

exm2 = [13, 98, 125, 191, 22, 9, 91, 78, 242]
print("\n Original exm2 = ", exm2)

exm2.sort(reverse = True)
print("Descending = ", exm2)

 Original =  [13, 98, 125, 191, 22, 9, 91, 78, 242]
Ascending =  [9, 13, 22, 78, 91, 98, 125, 191, 242]

 Original exm2 =  [13, 98, 125, 191, 22, 9, 91, 78, 242]
Descending =  [242, 191, 125, 98, 91, 78, 22, 13, 9]

Python sort List of Strings Examples

This Python section shows how to sort string list items in ascending and descending order.

In this example, first, we declared strings. Next, we used the list function to sort them in ascending order. Here, it uses alphabetical order to arrange the string items.

Fruit = ['Orange', 'Banana', 'Watermelon', 'Kiwi', 'Grape', 'Blackberry']

Fruit.sort()

print(Fruit)
['Banana', 'Blackberry', 'Grape', 'Kiwi', 'Orange', 'Watermelon']

This Python example method sorts the string and integer items in Ascending.

Fruits = ['Apple', 'Orange', 'Banana', 'Kiwi', 'Grape', 'Blackberry']
numbers = [9, 4, -5, 0, 22, -1, 2, 14]

print(Fruits)
print(numbers)

print("\n---Result---")
Fruits.sort()
print(Fruits)

numbers.sort()
print(numbers)
['Apple', 'Orange', 'Banana', 'Kiwi', 'Grape', 'Blackberry']
[9, 4, -5, 0, 22, -1, 2, 14]

---Result---
['Apple', 'Banana', 'Blackberry', 'Grape', 'Kiwi', 'Orange']
[-5, -1, 0, 2, 4, 9, 14, 22]

Python sort List in Descending Order using reverse

In this example, we used the reverse = True option inside the function. It means this example returns the reverse order of the above example.

fruitli = ['orange', 'banana', 'apple', 'kiwi', 'grape']
print(fruitli)

fruitli.sort()
print("\nAscending = ", fruitli)

# Descending Order
fruitli.sort(reverse = True)
print(fruitli)

Descending order Elements output


['orange', 'banana', 'apple', 'kiwi', 'grape']

Ascending =  ['apple', 'banana', 'grape', 'kiwi', 'orange']
Descending =  ['orange', 'kiwi', 'grape', 'banana', 'apple']

Python sort list using key argument & custom function

Using this method on list items has another argument called a key. It accepts any built-in method to determine the sorting factor. In this example, we created a user-defined function called 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 each word length in descending.

def length(str):
    return len(str)

fruits = ['apple', 'oranges', 'blackberry', 'kiwi', 'cherry']
print("\nOriginal = ", fruits)

fruits.sort(key = length)
print("Asc  = ", fruits)

fruits.sort(reverse = True, key = length)
print("Desc = ", fruits)

Original =  ['apple', 'oranges', 'blackberry', 'kiwi', 'cherry']
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 len function

This Python list sort method example is the same as the above example. However, we are using the built-in common len function. It means the first one organizes the list based on word length in ascending — the second one in Descending order using their length.

fruitsLi = ['oranges', 'blackberry', 'apple', 'kiwi', 'cherry']
print("\n Original = ", fruitsLi)

fruitsLi.sort(key = len)
print("\nAscending = ", fruitsLi)

fruitsLi.sort(reverse = True, key = len)
print("Descending= ", fruitsLi)

 Original =  ['oranges', 'blackberry', 'apple', 'kiwi', 'cherry']

Ascending =  ['kiwi', 'apple', 'cherry', 'oranges', 'blackberry']
Descending=  ['blackberry', 'oranges', 'cherry', 'apple', 'kiwi']

How to sort mixed List items in Python?

Let me use it on Mixed Elements.

MixedLi = ['apple',  1, 5, 'Kiwi', 'Mango']

MixedLi.sort()

print("The Items After are : \n", MixedLi)

It is throwing an error because it can’t apply < operation on string and int.

Traceback (most recent call last):
  File "/Users/suresh/Desktop/simple.py", line 3, in <module>
    ........
TypeError: '<' not supported between instances of 'int' and 'str'
>>> 

How to sort Nested List Items in Python?

The following examples help you understand this Python sort function on the nested list items.

This time, we used the function on the Nested. Here, it uses the first value in each nested one to organize items in ascending order.

Mixed = [[71, 222], [222, 13], [14, 15], [99, 77]]

Mixed.sort()

print(Mixed)
[[14, 15], [71, 222], [99, 77], [222, 13]]

sort nested list items using user defined function

You don’t have to restrict yourself by 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. It means the first code snippet orders the items based on the second value in a nested list — the second line sorts in descending using the second item.

def second(value):
    return value[1]

mixed = [[17, 222], [222, 13], [14, 151], [99, 77]]
print("\n Original = ", mixed)

mixed.sort(key = second)
print("\nAscending = ", mixed)

mixed.sort(reverse = True, key = second)
print("Descending = ", mixed)

 Original =  [[17, 222], [222, 13], [14, 151], [99, 77]]

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 order 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, it was sorting the items by the second item.

def second(value):
    return value[1]

mixed = [[17, 222, 15], [222, 13, 55], [14, 151, 31], [99, 77, 9]]
print("\nOriginal = ", mixed)

mixed.sort(key = second)
print("\nAscending = ", mixed)

# Descending Order
mixed.sort(reverse = True, key = second)
print("Descending = ", mixed)

Original =  [[17, 222, 15], [222, 13, 55], [14, 151, 31], [99, 77, 9]]

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.

def third(value):
    return value[2]

mixed = [[17, 222, 15], [222, 13, 55], [14, 151, 31], [99, 77, 9]]
print("\n Original = ", mixed)

mixed.sort(key = third)
print("\nAscending = ", mixed)

mixed.sort(reverse = True, key = third)
print("Descending = ", mixed)

 Original =  [[17, 222, 15], [222, 13, 55], [14, 151, 31], [99, 77, 9]]

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]]

Python sort Dynamic Integers List Example

This program is the same as the first example. However, this time we are allowing the user to enter the length. Next, we used For Loop to add numbers to it.

Lastly, we used this Python 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)
Python Sort List Function 5

In this program, we used the reverse argument to order the elements in the Descending.

numLi = []

number = int(input("Please enter the Number of Elements: "))
for i in range(1, number + 1):
    item = int(input("%d Item : " %i))
    numLi.append(item)

print("\nBefore : ", numLi)
numLi.sort(reverse = True)
print("Descending : ", numLi)
Please enter the Number of Elements: 5
1 Item : 25
2 Item : 33
3 Item : 12
4 Item : 87
5 Item : 20

Before :  [25, 33, 12, 87, 20]
Descending :  [87, 33, 25, 20, 12]

How to sort the user entered string list of words?

It allows users to enter their own strings or words. Next, we used it to order them in ascending.

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)

print("\nBefore : ", strSL)
strSL.sort()
print("After : ", strSL)
Please enter the Total Number of Elements: 4
1 Element : kiwi
2 Element : dragon
3 Element : apple
4 Element : banana

Before :  ['kiwi', 'dragon', 'apple', 'banana']
After :  ['apple', 'banana', 'dragon', 'kiwi']

sort 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 using the 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)

print("\nBefore : ", str1)
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 : balckberry

Before :  ['cherry', 'apple', 'orange', 'kiwi', 'balckberry']
Descending :  ['orange', 'kiwi', 'cherry', 'balckberry', 'apple']
Length :  ['balckberry', 'orange', 'cherry', 'apple', 'kiwi']