Python list sort() function is used to sort a list in ascending, descending or user defined order.

To sort the list in ascending order

List_name.sort()This will sort the given list in ascending order.
Python

This function is used to sort list of integers, floating point number, string and others.

numbers = [8, 5, 7, 9]   # Sorting list of Integers in ascending numbers.sort()   print(numbers)
Python

Output

[5, 7, 8, 9]
Bash

Example 2:

strs = ["gpkumar", "code", "ide", "practice"]   # Sorting list of Integers in ascending strs.sort()   print(strs)
Python

Output

['code', 'ide', 'practice', 'gpkumar']
Bash

To sort the list in descending order

Example:

list_name.sort(reverse=True)This will sort the given list in descending order
Python
numbers = [8, 5, 7, 9]   # Sorting list of Integers in descending numbers.sort(reverse = True)   print(numbers)
Python

Output

[9, 8, 7, 5]
Bash

Sorting user using user defined order

list_name.sort(key=…, reverse=…) – it sorts according to user’s choice
Python

Example

# Python program to demonstrate sorting by user's # choice   # 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 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)
Python

Output

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