The provided Python code offers two distinct approaches for sorting a list of numbers in descending order. The first method involves using the sort() method, which directly modifies the original list in place by sorting it in descending order. The second method employs the sorted() function to create a new list with the elements sorted in descending order, leaving the original list unchanged. Both approaches use a sample list [5, 2, 8, 1, 6] for demonstration. In the first case, the sort() method with the reverse=True parameter is applied, while in the second case, the sorted() function with the same parameter is used. The resulting sorted lists are then printed, showcasing the numbers arranged from highest to lowest. This code provides flexibility for users to choose the method that best aligns with their specific requirements.
Source code
# Sample list
original_list = [5, 2, 8, 1, 6]
# Sort the list in descending order in-place
original_list.sort(reverse=True)
# Print the result
print("Descending Order:", original_list)
Description
- Initialize the List:
original_list = [5, 2, 8, 1, 6]
A sample list of numbers is created. This list, original_list, is the one we want to sort in descending order.
- Sort In-Place using
sort()method:
original_list.sort(reverse=True)
The sort() method is called on original_list with the reverse=True parameter. This sorts the list in descending order in-place, meaning it modifies the original list directly.
- Print Result of In-Place Sorting:
print("Descending Order:", original_list)
The sorted list is printed, showing the elements arranged in descending order.
- Sort Using
sorted()function (Creating a new list):
descending_order = sorted(original_list, reverse=True)
The sorted() function is used to create a new list, descending_order, containing the elements of original_list sorted in descending order. The original list remains unchanged.
- Print Result of Sorting with
sorted()function:
print("Original List:", original_list) print("Descending Order:", descending_order)
The original list and the newly created sorted list are printed, demonstrating the sorting without modifying the original list.
In summary, the code provides two methods for sorting a list of numbers in descending order: one modifies the original list in-place using the sort() method, and the other creates a new sorted list using the sorted() function while leaving the original list unchanged. The result is printed for both cases, offering flexibility for users to choose the method that best fits their needs.
Screenshot

