How to sort list of strings alphabetically in Python : Methods

In this tutorial, you will learn the different methods to alphabetically sort a list of strings in Python.

Let’s create a simple list of strings.

list_strings = ["ABC","GHI","JKL","DEF"]

Output

["ABC","GHI","JKL","DEF"]

Different Methods to Sort list of strings alphabetically in python

Method 1: Using the sort() function

Invoke the sort() function on your list of strings to sort the string alphabetically.

list_strings = ["ABC","GHI","JKL","DEF"]
list_strings.sort()
print(list_strings)

Output

['ABC', 'DEF', 'GHI', 'JKL']

Method 2: Use the sorted() function with key

The other method is the use of the sorted() function with the key. The key defines how the strings will be ordered. Here the lowercase for each strings will be used to sort them.

list_strings = ["ABC","GHI","JKL","DEF"]
sorted(list_strings,key=str.lower)

Output

['ABC', 'DEF', 'GHI', 'JKL']

Method 3: Sorting the strings in descending order

The above two methods were sorting the list of strings in alphabetical order by default. Pass an extra parameter reverse=True to sort the strings in descending order.

list_strings = ["ABC","GHI","JKL","DEF"]
sorted(list_strings,reverse=True)

Output

['JKL', 'GHI', 'DEF', 'ABC']

 

Complete code

# sort list of strings in python
print("Method 1","/n")
list_strings = ["ABC","GHI","JKL","DEF"]
list_strings.sort()
print(list_strings)
print("Method 2","/n")
list_strings = ["ABC","GHI","JKL","DEF"]
print(sorted(list_strings,key=str.lower))
print("Method 3","/n")
list_strings = ["ABC","GHI","JKL","DEF"]
print(sorted(list_strings,reverse=True))

Output

sorting list of strings
sorting list of strings

Conclusion

In this tutorial, you have learned the two methods to sort the list of strings alphabetically. The first method used the sort() function and the second method used the sorted() method. These two methods were sorting the list of strings in ascending order. You can pass an extra parameter reverse() to sort the list of strings in descending order.

Hi, I am CodeTheBest. Here you will learn the best coding tutorials on the latest technologies like a flutter, react js, python, Julia, and many more in a single place.

SPECIAL OFFER!

This Offer is Limited! Grab your Discount!
15000 ChatGPT Prompts
Offer Expires In:
close-link