Lists are a common data structure used to store sequences and/or collection of data in Python. Since lists are an ordered collection, it can be handy to know how to sort a list in ascending or descending order.
- Why sort lists or any data for that matter?
- The list
- The built-in
In general, data presented in a sorted order is more intuitive to look at and infer from. Additionally, some problems become easier to solve when the data is already sorted. For example - Binary search - Searching for an element in a list would take linear time if the list is not sorted but it takes only logarithmic time if the list is already sorted.
To sort the list in-place, use the list
sort() function. It has the following syntax -
It sorts the list in-place and does not return any value.
The optional parameter
reverse specifies whether to sort the list in descending order or not (and is
False by default) whereas the
key option parameter allows you to pass a custom function to determine the sorting order.
Here's an example -
# create a list ls = [3, 5, 1, 2, 4, 7, 6] # sort the list ls.sort() # display the list print(ls)
[1, 2, 3, 4, 5, 6, 7]
The list got sorted in-place.
Let's now sort the above list in descending order. For this, pass
reverse=True to the
# create a list ls = [3, 5, 1, 2, 4, 7, 6] # sort the list in descending order ls.sort(reverse=True) # display the list print(ls)
[7, 6, 5, 4, 3, 2, 1]
The list is now sorted in descending order
If you do not want to modify the original list, you can use the Python built-in
sorted() function. Its syntax is very similar to the list
sort() function -
sorted(iterable, reverse=False, key=None)
It returns a sorted copy of the original list.
Let's look at this method in action.
# create a list ls = [3, 5, 1, 2, 4, 7, 6] # sort the list res_ls = sorted(ls) # display the original list print("Original list - ", ls) # display the resulting list print("Resulting list - ", res_ls)
Original list - [3, 5, 1, 2, 4, 7, 6] Resulting list - [1, 2, 3, 4, 5, 6, 7]
The original list is unaffected and the returned list is sorted.
We looked at two methods to sort a list in Python (both with similar parameters). The key takeaways from this tutorial are-
- To sort the list in-place use the list
- To keep the original list unaltered use the Python built-in
sorted()function which returns a sorted copy of the original list.
sort() and the
sorted() functions take the optional parameters
key parameter can be very useful if you're looking to apply for custom sorting logic on a list. Refer to the tutorial - Python List Sort - With Examples for examples on how to perform such sort operations using the