613
In this article we show a way of sorting a list in descending order in python
Example
We use a for loop to add numbers to the Python list using the apppend method
We then use the sort method to sort the List items in ascending order.
We then use the reverse method to reverse the list
# Sort a List in Descending Order myList = [] Number = int(input("Please enter the Number of List Elements: ")) for i in range(1, Number + 1): value = int(input("Please enter the Value of Element %d : " %i)) myList.append(value) myList.sort() myList.reverse() print('Sorted List in Descending Order is') print(myList)
When you run this you will see something like this
>>> %Run listascend.py >>> %Run listdescend.py Please enter the Number of List Elements: 6 Please enter the Value of Element 1 : 10 Please enter the Value of Element 2 : 50 Please enter the Value of Element 3 : 30 Please enter the Value of Element 4 : 20 Please enter the Value of Element 5 : 60 Please enter the Value of Element 6 : 40 Sorted List in Descending Order is [60, 50, 40, 30, 20, 10]