Python – Sort a List Alphabetically

Python – Sort a List Alphabetically

To sort a given list of strings alphabetically in Python, you can use list sort() method.

Given a list of strings, call sort() method on the list. The sort() method sorts the list of strings alphabetically in ascending order.

For example, if my_list is the given list of strings, then the syntax of the statement to sort this list alphabetically is given below.

my_list.sort()

The sort() method sorts the list of strings in place.

1. Sort list alphabetically in ascending order

Let us take a list of strings in my_list and sort them alphabetically in ascending order using sort() method.

By default sort() method sorts in ascending order.

Python Program

my_list = ["cherry", "banana", "apple", "fig"]
print(f"Given list  : {my_list}")

my_list.sort()
print(f"Sorted list : {my_list}")
Run Code Copy

Output

Given list  : ['cherry', 'banana', 'apple', 'fig']
Sorted list : ['apple', 'banana', 'cherry', 'fig']

If you observe the output, the string items in the sorted list are in alphabetical order.

2. Sort list alphabetically in descending order

Now, we shall sort the list of strings in my_list alphabetically in descending order using sort() method.

To sort in descending order, pass the named argument reverse=True to the sort() method.

Python Program

my_list = ["cherry", "banana", "apple", "fig"]
print(f"Given list  : {my_list}")

my_list.sort(reverse=True)
print(f"Sorted list : {my_list}")
Run Code Copy

Output

Given list  : ['cherry', 'banana', 'apple', 'fig']
Sorted list : ['fig', 'cherry', 'banana', 'apple']

If you observe the output, the string items in the sorted list are in alphabetical descending order.

Summary

In this tutorial of Python Lists, we have seen how to alphabetically sort a list of strings in ascending or descending order, using sort() method, with examples.

Related Tutorials

Code copied to clipboard successfully 👍