Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
sort
sorted()

What is the Python sorted() function?

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.

Answers Code

The sorted() function in python returns a sorted list of the iterable object i.e. list, dictionary, and tuple. By default, it sorts the given object in ascending order.

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

svg viewer
tuple = (2, -1, 7, 5)
list = sorted(tuple)
print(list)

Algorithm used by sorted()

The Python sorted() uses the Timsort algorithm which is a hybrid sorting algorithm, derived from merge sort and insertion sort.

Syntax


sorted(iterable_object, key=key, reverse=False)

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.

touple1 = (2, -1, 7, 5)
print(sorted(touple1, reverse=True)) # Sort the list in descending order
# A callable function which returns the length of a string
def lengthKey(str):
return len(str)
touple2 = ("London", "Paris", "Copenhagen", "Melbourne")
# Sort based on the length of the elements
print(sorted(touple2, key=lengthKey))

RELATED TAGS

python
sort
sorted()
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.

Answers Code
Keep Exploring