Python - Sort List of Strings
Python - Sort List of Strings
To sort list of strings in ascending or descending lexicographic order, use list.sort() method.
If all the elements of the given list are comparable, then sort() method, by default sorts the list in place in ascending order. To sort in descending order, pass the named argument reverse to sort method.
In this tutorial, you shall learn how to use sort() method to sort strings, in the following examples.
Examples
1. Sort list of strings in ascending order
In this example, we take a list of strings. We have to arrange these strings in the list in ascending lexicographical order. The best example for the order would be, how words appear in an English Dictionary.
Lexicographically, 'a' is smaller than 'b', 'b' is smaller than 'c' and so on.
Python Program
my_list = ['cherry', 'mango', 'apple', 'orange', 'banana']
my_list.sort()
print(my_list)
Output
['apple', 'banana', 'cherry', 'mango', 'orange']
Sort operation modifies the list as the sorting operation takes in-place. If you would like to keep the original list unchanged, you may use list.copy() method to make a copy and then sort the list. In the following example, we shall demonstrate how to make a copy and then sort the list of strings.
Python Program
my_list = ['cherry', 'mango', 'apple', 'orange', 'banana']
sorted_list = my_list.copy()
sorted_list.sort()
print(my_list)
print(sorted_list)
Output
'cherry', 'mango', 'apple', 'orange', 'banana']
['apple', 'banana', 'cherry', 'mango', 'orange']
2. Sort list of strings in descending order
In our previous example, we have sorted strings in ascending order. In this example, we will learn how to sort strings in descending order. Pass reverse=True
as argument to list.sort() method, and the list sorts itself in descending order.
Python Program
my_list = ['cherry', 'mango', 'apple', 'orange', 'banana']
my_list.sort(reverse=True)
print(my_list)
Output
['orange', 'mango', 'cherry', 'banana', 'apple']
Summary
In this tutorial of Python Examples, we learned how to sort strings in a list using list.sort() method.