CARVIEW |
Select Language
HTTP/2 200
cache-control: public, max-age=300, stale-while-revalidate=604800
referrer-policy: strict-origin-when-cross-origin
x-app-version: v251008-h-251010-1202
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
x-xss-protection: 1; mode=block
x-app-type: Learn
x-middleware-rewrite: /answers/howdev/what-is-the-python-list-sort
x-nextjs-cache: MISS
etag: W/"ulltyxqv1sy683"
content-type: text/html; charset=utf-8
x-cloud-trace-context: 8055edadb85f7a98c248028f06fcd82a
date: Sun, 12 Oct 2025 08:20:09 GMT
server: Google Frontend
via: 1.1 google
vary: Accept-Encoding
content-encoding: gzip
x-cache-status: miss
alt-svc: h3=":443"; ma=2592000,h3-29=":443"; ma=2592000
What is the Python list sort()? 
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.
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:
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 stringdef lengthKey(str):return len(str)list2 = ["London", "Paris", "Copenhagen", "Melbourne"]# Sort based on the length of the elementslist2.sort(key=lengthKey)print(list2)
Relevant Answers
Explore Courses
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved