Python – Sort List Elements – sort() Function with Examples

sort() function is used to sort the items of a list. List can be sort different ways ascending or descending order. This is a part of python programming language and a hand tool for quickly sort the list items. There is another built in function named sorted() can be use for sorting purpose. The main difference between sort() and sorted() is that sort() is a list method which does no return anything and only sort the items and on the other side sorted() is a function which return the sorted list.

We can easily sort a lists. There is a list (3, 8, 2, 5, 1) and we can sort it with sort() method if we did not pass any argument the method will sort the list in ascending order and we will see an output (1, 2, 3, 5, 8).
Ascending order shows that value item starts from smaller values to larger vales. Which is the above case.
Descending order means that value will be sort from larger value to smaller value.

We can sort any list that contains numbers or characters or words.

Syntax of sort() Function

The syntax of sort() function in Python is:

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

key and reverse are the arguments. The sort() method can be used without these arguments.


Parameters of sort() Function in Python

key – Where key is an argument which takes a function and serve it as a key and compare the items and sort the final result. Key parameter is optional.
reverse – Where reverse is an argument which can be assigned true or false and there two value determine the order of the sorted list. Reverse parameter is also optional.



sort() function is available and compatible with both Python 2.x and 3.x. This function is one of python list methods.


Return Value of sort() Function in Python

sort() function just sort the items of the list and did not return anything.


Python sort() Function Example 1

There is a list of fruits and we are going to sort this list without passing an argument and the list will be sorted in ascending order.

# a fruits list
fruit = ['apple', 'grapes', 'banana']
# Sort the list
#Print the sorted fruit list

['apple', 'banana', 'grapes']
After sorting banana and grapes change heir positions.


Python sort() Function Example 2

Now we are sorting a list of Numbers (4, 8, 2, 5, 1, 10) and we are going to reverse its order (descending) using a reverse argument.

# a num list
num = [4, 8, 2, 5, 1, 10]
# Sort the list
#Print the sorted fruit list

[10, 8, 5, 4, 2, 1]