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
- reverse(optional): reverse=True will sort the list descending. The default is reverse=False.
- 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() 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.
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.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.