How to sort a list in descending order
How to sort a list in descending order.
Here is a step-by-step tutorial on how to sort a list in descending order:
Start by creating a list of elements that you want to sort. For example, let's consider the following list:
[5, 2, 8, 1, 9].There are multiple ways to sort a list in descending order. One of the simplest methods is to use the
sort()method in Python. This method sorts the list in-place, meaning it modifies the original list. To sort the list in descending order, you can pass thereverse=Trueargument to thesort()method. Here's an example:my_list = [5, 2, 8, 1, 9]
my_list.sort(reverse=True)
print(my_list) # Output: [9, 8, 5, 2, 1]In this example, the
sort()method sorts the listmy_listin descending order, and the resulting sorted list is printed.Another way to sort a list in descending order is by using the
sorted()function. Unlike thesort()method, thesorted()function returns a new sorted list and leaves the original list unchanged. You can also pass thereverse=Trueargument to thesorted()function to sort the list in descending order. Here's an example:my_list = [5, 2, 8, 1, 9]
sorted_list = sorted(my_list, reverse=True)
print(sorted_list) # Output: [9, 8, 5, 2, 1]In this example, the
sorted()function sorts the listmy_listin descending order and assigns the sorted list to the variablesorted_list. The resulting sorted list is then printed.If you're working with a list of strings, you can use the
sort()method orsorted()function in the same way to sort the list in descending alphabetical order. Here's an example:my_list = ['apple', 'banana', 'cherry', 'date']
my_list.sort(reverse=True)
print(my_list) # Output: ['date', 'cherry', 'banana', 'apple']
sorted_list = sorted(my_list, reverse=True)
print(sorted_list) # Output: ['date', 'cherry', 'banana', 'apple']In this example, the list
my_listis sorted in descending alphabetical order using both thesort()method andsorted()function.
That's it! You now know how to sort a list in descending order using different methods in Python.