What is the Python list sort()?

The sort() function is a member of the list data structure in Python. By default, it sorts the elements of a list in ascending order.

svg viewer
list = [20, 5, -10, 300]
list.sort()
print(list)

In the case of strings and characters, sorting is done based on their ASCII values.

Sorting

The Python list sort() has been using the Timsort algorithm since version 2.3.

This algorithm has a runtime complexity of O(n.logn).

The function has two optional attributes which can be used to specify a customized sort:

svg viewer

The key attribute requires a callable function as its input. The function will specify the sorting criteria.

list1 = [20, 5, -10, 300]
list1.sort(reverse=True) # Sort the list in descending order
# A callable function which returns the length of a string
def lengthKey(str):
return len(str)
list2 = ["London", "Paris", "Copenhagen", "Melbourne"]
# Sort based on the length of the elements
list2.sort(key=lengthKey)
print(list2)
Copyright ©2024 Educative, Inc. All rights reserved