Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

What is the Python list sort()?

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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)

RELATED TAGS

Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring