Python Program to Sort a List in Descending Order
Beginner · Searching and sorting
Descending order runs from the largest value to the smallest. This program sorts numbers and names in descending order with reverse=True, and shows the difference between sorted(), which makes a new list, and sort(), which changes the list itself.
Program
Original list: [42, 7, 19, 88, 3, 56] Descending order: [88, 56, 42, 19, 7, 3] After numbers.sort(reverse=True): [88, 56, 42, 19, 7, 3] Names, Z to A: ['arjun', 'Zoya', 'Meera', 'Kabir'] Ignoring case: ['Zoya', 'Meera', 'Kabir', 'arjun']
How it works
reverse=Truetellssorted()andsort()to put the largest value first.sorted(numbers, ...)returns a new list, sonumbersis still in its original order when it is printed.numbers.sort(...)sorts the list in place and returnsNone, so do not writenumbers = numbers.sort().- Strings compare by character codes, and every capital letter comes before every small letter, so "arjun" is placed first in Z to A order.
key=str.lowercompares the names as if they were all small letters, which gives the order people expect.
Other ways to write it
Without sort functions
Descending order: [88, 56, 42, 19, 7, 3]
Each position i is compared with every later position, and any bigger number is swapped forward, so the largest values collect at the front.
Sort ascending, then reverse
Descending order: [88, 56, 42, 19, 7, 3] Using slicing: [88, 56, 42, 19, 7, 3]
Sorting from smallest to largest and then reversing gives the same result in two steps.
Try it yourself
Sort the list [3.5, -2, 10, 0, 7.25] in descending order and check where the negative number ends up.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises