Sorting a List Alphabetically in Python
In Python, you can sort a list in alphabetical order using two main methods:
sort()
method — This method modifies the original list in place, meaning it changes the order of the original list and does not create a new sorted version.sorted()
function — This function creates a new sorted list and returns it, leaving the original list unchanged.
Example using sort()
method:
my_list = ["apple", "banana", "cherry", "date"] my_list.sort() # Sort the list alphabetically print(my_list)
The output of the above code will be:
['apple', 'banana', 'cherry', 'date']
Example using sorted()
function:
my_list = ["apple", "banana", "cherry", "date"] sorted_list = sorted(my_list) # Create a new sorted list print(sorted_list)
The output of this code will be:
['apple', 'banana', 'cherry', 'date']
Sorting in Reverse Alphabetical Order
If you want to sort the list in reverse alphabetical order (i.e., descending order), you can pass the reverse=True
parameter to either the sort()
method or the sorted()
function.
Using sort()
method with reverse=True
:
my_list = ["apple", "banana", "cherry", "date"] my_list.sort(reverse=True) # Sort the list in reverse alphabetical order print(my_list)
The output will be:
['date', 'cherry', 'banana', 'apple']
Using sorted()
function with reverse=True
:
my_list = ["apple", "banana", "cherry", "date"] sorted_list = sorted(my_list, reverse=True) # Create a new sorted list in reverse order print(sorted_list)
The output will be:
['date', 'cherry', 'banana', 'apple']
Both methods allow you to sort lists either alphabetically or in reverse alphabetical order, depending on your needs.