To sort a list in descending order in Python, you can use the built-in sorted
function with a custom reverse flag or a custom key function.
In this example,
numbers
with integer values.sorted
function with the reverse=True
flag to sort the list in descending order.sorted
function returns a new list sorted in descending order, leaving the original list unchanged.numbers = [5, 2, 8, 1, 3]
sorted_numbers = sorted(numbers, reverse=True)
print('Sorted list in descending order:', sorted_numbers)
Sorted list in descending order: [8, 5, 3, 2, 1]
In this example,
words
with string values.sorted
function with a custom key function that sorts strings based on length in descending order.words = ['banana', 'apple', 'cherry']
sorted_words = sorted(words, key=len, reverse=True)
print('Sorted list in descending order:', sorted_words)
Sorted list in descending order: ['banana', 'cherry', 'apple']
In this tutorial, we learned How to Sort a List in Descending Order in Python language with well detailed examples.