In this Python tutorial, you will learn how to sort a given list in ascending or descending order of elements in the list, using sorted() builtin function.
Sort List in Python using sorted()
You can sort a list in ascending or descending order using sorted() builtin function. sorted() method does not modify the original list, but returns a new list with sorted elements, where the elements are from the original list.
Programs
1. Sort List in Ascending Order using sorted()
In the following program, we take a list of integers, and sort them in ascending order using sorted() function.
Pass the list as argument to sorted() function, and pass no other parameters.
main.py
#initialize list
nums = [21, 28, 14, 96, 84, 65, 74, 31]
#sort list
sortedList = sorted(nums)
#print sorted list
print(sortedList)
Output
[14, 21, 28, 31, 65, 74, 84, 96]
Reference tutorials for the above program
2. Sort List in Descending Order using sorted()
In the following program, we take a list of integers, and sort them in descending order using sorted() function.
For sorted() function to sort elements in descending order, pass reverse=True
as argument.
main.py
#initialize list
nums = [21, 28, 14, 96, 84, 65, 74, 31]
#sort list
sortedList = sorted(nums, reverse=True)
#print sorted list
print(sortedList)
Output
[96, 84, 74, 65, 31, 28, 21, 14]
Reference tutorials for the above program
Conclusion
In this Python Tutorial, we learned how to sort a list in Python using sorted() builtin function, in ascending or descending order.