Skip to main content
Practice

Sorting List Elements with the sort() Function

In Python, the sort() function sorts the elements of a list based on a specified criterion.

It modifies the original list in place, meaning it does not return a new list but instead changes the order of the existing one.


How to Use the sort() Function

By default, the sort() function sorts the elements of a list in ascending order.

To sort in descending order, pass sort(reverse=True).

Example of sort() Function
numbers = [3, 1, 4, 1, 5, 9, 2]
# Ascending order
numbers.sort()
# [1, 1, 2, 3, 4, 5, 9]
print("sorted:", numbers)

# Descending order
numbers.sort(reverse=True)
# [9, 5, 4, 3, 2, 1, 1]
print("reverse=True:", numbers)

Specifying a Sorting Criterion with the key Parameter

You can provide a custom sorting rule using the key parameter. This allows you to define how elements are compared.

For example, to sort a list of strings by their length, you can pass key=len to the sort() function

Custom Sorting: Sort by String Length
words = ['banana', 'pie', 'Washington', 'apple']

# Sort by string length
words.sort(key=len)

# Output: ['pie', 'apple', 'banana', 'Washington']
print(words)

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.