How to sort a Python list in reverse order?
To reverse sort a Python list, you can use the list’s reverse() method. This method will directly modify the original list, rearranging its elements in reverse order.
Here is an example code:
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5]
my_list.reverse()
print(my_list)
The output result is:
[5, 6, 2, 9, 5, 1, 4, 1, 3]
If you want to create a new list in reverse order without modifying the original list, you can use the [::-1] slicing operator. This operator will create a new list with elements that are in reverse order of the original list.
Here is an example code using slice operator for reverse sorting:
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5]
reversed_list = my_list[::-1]
print(reversed_list)
The result is output as:
[5, 6, 2, 9, 5, 1, 4, 1, 3]