Skip to main content

sort()

The sort() method in Python is a built-in function that is used to sort the elements in a list in ascending order by default. It modifies the list in place and does not return a new sorted list. You can also use the optional parameters to customize the sorting behavior, such as reverse=True to sort in descending order or key to specify a custom sorting key function.

Parameter Values

Parameter Description
key

A function that will be called to transform the values before sorting.

reverse

A boolean value. If set to True, the list will be sorted in descending order.

Return Values

The sort() method does not return a value but sorts the list in place.

How to Use sort() in Python

Example 1:

The sort() method sorts the elements of a list in-place, in ascending order by default.

numbers = [4, 2, 1, 3]
numbers.sort()
print(numbers) # Output: [1, 2, 3, 4]
Example 2:

You can use the reverse parameter to sort in descending order.

numbers = [4, 2, 1, 3]
numbers.sort(reverse=True)
print(numbers) # Output: [4, 3, 2, 1]
Example 3:

You can also specify a custom sorting function using the key parameter.

fruits = ['apple', 'banana', 'cherry', 'date']
fruits.sort(key=lambda x: x[1])
print(fruits) # Output: ['banana', 'cherry', 'apple', 'date']