Here are 2 ways to sort a list in Python:
1. Using the ‘sorted()’ function (returning a new sorted list):
To sort a list in an ascending order:
my_list = ["D", "X", "A", "Z", "E"]
sorted_list = sorted(my_list)
print(sorted_list)
The result:
['A', 'D', 'E', 'X', 'Z']
To sort a list in a descending order:
my_list = ["D", "X", "A", "Z", "E"]
sorted_list = sorted(my_list, reverse=True)
print(sorted_list)
The result:
['Z', 'X', 'E', 'D', 'A']
2. Using the ‘sort()’ method (sorting the existing list in place):
To sort a list in an ascending order:
my_list = ["D", "X", "A", "Z", "E"]
my_list.sort()
print(my_list)
The result:
['A', 'D', 'E', 'X', 'Z']
To sort a list in a descending order:
my_list = ["D", "X", "A", "Z", "E"]
my_list.sort(reverse=True)
print(my_list)
The result:
['Z', 'X', 'E', 'D', 'A']