Using the `sort()` Method
tags: #python/documentation/data_structures/lists/methods
You can sort elements in a list by using the dot notation[1] to call the sort() function.
a_list.sort(key=None, reverse=False)
The sort() method sorts the items of a list in ascending or descending order in-place (i.e., the original list is modified, and the sorted order is applied directly to the elements within the same list object without creating a new list).
To create a sorted copy of the list, we can se the [[sorted() Method]].
By default, sort() arranges the elements in ascending order (from smallest to largest).
Example:
# Example list
numbers = [4, 2, 8, 1, 5]
# Using sort() to sort the list in-place
numbers.sort()
# Print the sorted list
print(numbers)
[1, 2, 4, 5, 8]
How to sort in descending order
To sort a list in-place in descending order, we can set the reverse parameter to True.
a_list.sort(key=None, reverse=True)
Using the Key Parameter
The key parameter is an optional. This is where you can provide a function that specifies how elements in the list should be sorted. This can be a built-in or user-defined function or a lambda expression.
a_list.sort(key=<some function>, reverse=False)
The default is None, which means the items are sorted based on their natural order.
Example:
# Example list of strings
fruits = ["banana", "apple", "orange", "kiwi"]
# Sort the list based on the length of each string (built-in function)
fruits.sort(key=len)
print(fruits)
['kiwi', 'apple', 'banana', 'orange']
In Python, the dot notation is used for method calls. When you have an object, you use the dot notation to access its methods and attributes. ↩︎