Sort a List in Descending Order in Python

To sort a list in descending order in Python, you can use the sort() method with the reverse=True parameter for in-place sorting or the sorted() function with reverse=True to return a new sorted list.


Examples

1. Sort a List in Descending Order Using sort() Method

The sort() method sorts the list in-place, modifying the original list directly. By setting reverse=True, we get a descending order sort.

</>
Copy
# Creating a list of numbers
numbers = [5, 2, 9, 1, 7]

# Sorting the list in descending order
numbers.sort(reverse=True)

# Printing the sorted list
print("Sorted List:", numbers)

Here, we define a list numbers containing five integers. We use the sort() method on numbers and pass reverse=True to sort the elements in descending order. Since sort() modifies the list in-place, no new list is created.

Output:

Sorted List: [9, 7, 5, 2, 1]

2. Sort a List in Descending Order Using sorted() Function

The sorted() function returns a new sorted list without modifying the original list.

</>
Copy
# Creating a list of numbers
numbers = [8, 3, 6, 2, 10]

# Sorting using sorted() in descending order
sorted_numbers = sorted(numbers, reverse=True)

# Printing the sorted list
print("Original List:", numbers)
print("Sorted List:", sorted_numbers)

Here, we define a list numbers and pass it to the sorted() function with reverse=True. This function returns a new list sorted_numbers without modifying numbers. The original list remains unchanged.

Output:

Original List: [8, 3, 6, 2, 10]
Sorted List: [10, 8, 6, 3, 2]

3. Sorting a List of Strings in Descending Order

We can also sort a list of strings in descending order using the same methods.

</>
Copy
# Creating a list of strings
fruits = ["apple", "banana", "cherry", "date"]

# Sorting in descending order
fruits.sort(reverse=True)

# Printing the sorted list
print("Sorted List:", fruits)

The fruits list contains string values. When sorted in descending order, Python arranges the elements based on lexicographical order (alphabetical order but reversed). The sort() method modifies the list directly.

Output:

Sorted List: ['date', 'cherry', 'banana', 'apple']

Conclusion

  1. sort(reverse=True): Sorts the list in place and modifies the original list.
  2. sorted(iterable, reverse=True): Returns a new sorted list without changing the original.

If you want to modify the original list, use sort(). If you need a sorted copy while keeping the original intact, use sorted().