Skip to main content

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:

  1. 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].

  2. 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 the reverse=True argument to the sort() 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 list my_list in descending order, and the resulting sorted list is printed.

  3. Another way to sort a list in descending order is by using the sorted() function. Unlike the sort() method, the sorted() function returns a new sorted list and leaves the original list unchanged. You can also pass the reverse=True argument to the sorted() 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 list my_list in descending order and assigns the sorted list to the variable sorted_list. The resulting sorted list is then printed.

  4. If you're working with a list of strings, you can use the sort() method or sorted() 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_list is sorted in descending alphabetical order using both the sort() method and sorted() function.

That's it! You now know how to sort a list in descending order using different methods in Python.