Sort List in Python
You can sort a list in ascending or descending order using list.sort() or sorted(list).
sort() can accept a boolean argument called reverse which by default is False
and sorts the list in ascending order. If this parameter is given True
, the list shall be sorted in descending order.
Sort Python List in Ascending Order
We shall not provide any argument to sort(), hence the default operation of sorting the list in ascending order should happen.
example.py – Python Program
#initialize list aList = [21, 28, 14, 96, 84, 65, 74, 31] #sort list aList.sort() #print sorted list print(aList)Try Online
Output
[14, 21, 28, 31, 65, 74, 84, 96]
Sort Python List in Descending Order
We shall provide the value of reverse parameter of sort() as True
. Then the sorting will happen in Descending order.
example.py – Python Program
#initialize list aList = [21, 28, 14, 96, 84, 65, 74, 31] #sort list aList.sort(reverse=True) #print sorted list print(aList)Try Online
Output
[96, 84, 74, 65, 31, 28, 21, 14]
Little more about sort() and introduction to sorted()
sort() does perform in-place sorting. So, the original list is modified.
If you would like to keep the original list unchanged, you can use sorted(). sorted() returns the sorted list with doing any modifications to the original list.
example.py – Python Program
#initialize list aList = [21, 28, 14, 96, 84, 65, 74, 31] #sort list sortedList = sorted(aList) #print list print(aList) #print sorted list print(sortedList)Try Online
Output
[21, 28, 14, 96, 84, 65, 74, 31] [14, 21, 28, 31, 65, 74, 84, 96]
You can use the same parameter as we used with sort() to sort a list in descending order.
example.py – Python Program
#initialize list aList = [21, 28, 14, 96, 84, 65, 74, 31] #sort list sortedList = sorted(aList, reverse=True) #print list print(aList) #print sorted list print(sortedList)Try Online
Output
[21, 28, 14, 96, 84, 65, 74, 31] [96, 84, 74, 65, 31, 28, 21, 14]
Conclusion
In this Python Tutorial, we learned how to sort a list in Python using sort() and sorted() with the help of example programs.