Python List sort() Method

Python list sort() method is used to sort the elements of a list in ascending or descending order.

Syntax

list.sort(reverse=True|False, key=myFunc)

Parameters

  1. reverse(optional):  reverse=True will sort the list descending. The default is reverse=False.
  2. key(optional): It is the function to specify the sorting criteria.

Return Value

This method doesn’t return any value. First, it changes the original list.

If you want the original list, use sorted().

Example 1: How to Use List sort() MethodVisual Representation of Python List sort() Method

GoT = ['Jon', 'Tyrion', 'Daenerys']
GoT.sort()

print (GoT)

Output

'Daenerys', 'Jon', 'Tyrion']

Example 2: Sort in Descending order

To arrange descending order, we must add reverse=True in the sort() method’s parameter.Visual Representation of Sort list in Descending order

database = ["mongo", "sql", "pinecone"]

# sort the database
database.sort(reverse=True)

# print database
print('Sorted list (in Descending):', database)

Output

Sorted list (in Descending): ['sql', 'pinecone', 'mongo']

Example 3: Sort with custom function using key

This function also accepts a key function as an optional parameter. You can sort the given list based on the key function results.

list.sort(key=len)

See the code example below.

def customSorting(elem):
  return elem[1]


randomValues = [(11, 21), (19, 18), (46, 20), (29, 33)]

random.sort(key=customSorting)

print('Sorted list:', randomValues)

Output

Sorted list: [(19, 18), (46, 20), (11, 21), (29, 33)]

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.