Sort a List Alphabetically in Python

Document 对象参考手册Python3 Examples

To sort a list alphabetically in Python, you can use the following two methods:

  • sort() method-- That is, it directly modifies the original list without creating a new sorted copy. This method changes the order of the original list and does not return a new sorted list.
  • sorted() function-- It creates a new sorted list without modifying the original list. This function returns a new sorted list, and the original list remains unchanged.

Example of the sort() method:

Example

my_list = ["apple", "banana", "cherry", "date"]
my_list.sort()  # Sort in alphabetical order
print(my_list)

The output after executing the above code is as follows:

['apple', 'banana', 'cherry', 'date']
Example of the sorted() function:

Example

my_list = ["apple", "banana", "cherry", "date"]
sorted_list = sorted(my_list)  # Create a new sorted list
print(sorted_list)

The output after executing the above code is as follows:

['apple', 'banana', 'cherry', 'date']

Regardless of which method you choose, you can sort the list in alphabetical order. If you want to sort in reverse alphabetical order (descending), you can pass thereverse=Trueparameter.

sort() method:

Example

my_list = ["apple", "banana", "cherry", "date"]
my_list.sort(reverse=True)  # Sort in descending alphabetical order
print(my_list)

sorted() function:

Example

my_list = ["apple", "banana", "cherry", "date"]
sorted_list = sorted(my_list, reverse=True)  # Create a new sorted list in descending alphabetical order
print(sorted_list)

Document 对象参考手册Python3 Examples

Other Extensions