Python List sort() Method



The Python List sort() method arranges the objects of a list in ascending order, by default.

To change the order of these objects, this method takes two optional arguments. They can be used in the following ways −

  • The reverse parameter holds a "False" value by default, so when it is set to "True", the method arranges the elements in descending order.
  • The key parameter holds a None value by default. This parameter is used by the method to set a sorting criteria that differs from either ascending or descending order. The value set to the key parameter must always be a function (or other callable) that accepts one argument and returns a key to use for sorting purposes.

Syntax

Following is the syntax for the Python List sort() method −

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

Parameters

  • key − (Optional Parameter) Default key = None. A function to determine sorting criteria.
  • reverse − (Optional Parameter) Default reverse = False. If reverse = True, the objects are sorted in descending order.

Return Value

This method does not return any value but it changes from the original list.

Example

The following example shows the usage of the Python List sort() method. Here, we pass no arguments to execute the method by default.

aList = ['123', 'xyz', 'zara', 'abc', 'xyz']
aList.sort()
print("List : ", aList)

When we run above program, it produces following result −

List :  ['123', 'abc', 'xyz', 'xyz', 'zara']

Example

If we pass the reverse parameter as True to the method, the list is sorted in descending order. We can display the list to check the results as the method does not return any value.

aList = ['123', 'xyz', 'zara', 'abc', 'xyz']
aList.sort(reverse=True)
print("List : ", aList)

When we run the program above, the output is displayed as follows −

List :  ['zara', 'xyz', 'xyz', 'abc', '123']

Example

Now, if we pass a function defining a sorting criteria as a value to the key parameter, the method sorts the list based on the criteria.

In this example, let us create a list and call the sort() method on it. Here, we define a function that returns the third element (or the element at index 2) of the string object present in the list. This function is passed as a value to the key parameter of the sort() method. Therefore, the third elements of all the strings are compared, and the elements in the list are sorted in either ascending order or descending order (if reverse is set to True).

def func(key):
    return key[2]

aList = ['123', 'xyz', 'zara', 'abc', 'xyz']
aList.sort(key=func)
print("List : ", aList)

#reverse is set to True
aList.sort(reverse=True, key=func)
print("List : ", aList)

List :  ['123', 'abc', 'zara', 'xyz', 'xyz']
List :  ['xyz', 'xyz', 'zara', 'abc', '123']
python_lists.htm
Advertisements