Python program sort list elements for ascending and descending order; Through this tutorial, i am going to show you how to sort a list elements or items for ascending and descending order in python.
You can use the python inbuilt method name sort(), which is used to sort the elements/objects of the list in Ascending and Descending Order.
Basic Syntax of python sort() method:
list.sort()
Python Program to Sort List For Ascending and Descending Order
- Sort list in ascending order python
- Sort list in descending order python
Sort list in ascending order python
# List of integers num = [100, 200, 500, 600, 300] # sorting and printing num.sort() #print print(num) # List of float numbers fnum = [100.43, 50.72, 90.65, 16.00, 04.41] # sorting and printing fnum.sort() #print print(fnum) # List of strings str = ["Test", "My", "Word", "Tag", "Has"] # sorting and printing str.sort() #print print(str)
After executing the python program, the output will be:
[100, 200, 300, 500, 600] [4.41, 16.0, 50.72, 90.65, 100.43] ['Has', 'My', 'Tag', 'Test', 'Word']
As you know above, how to sort list elements in ascending order. Now you will read how to sort a list in descending order by using sort() method.
You pass reverse=True as an argument with sort() method to sort a list elements in descending order.
You can see the following program to sort a list element in descending order.
Sort list in descending order python
# List of integers num = [100, 200, 500, 600, 300] # sorting and printing num.sort(reverse=True) #print print(num) # List of float numbers fnum = [100.43, 50.72, 90.65, 16.00, 04.41] # sorting and printing fnum.sort(reverse=True) #print print(fnum) # List of strings str = ["Test", "My", "Word", "Tag", "Has"] # sorting and printing str.sort(reverse=True) #print print(str)
After executing the program, the output will be:
[600, 500, 300, 200, 100] [100.43, 90.65, 50.72, 16.0, 4.41] ['Word', 'Test', 'Tag', 'My', 'Has']