Sorting a list of strings is a common task in Python programming. It involves organizing strings or text items in a specific order, either ascending or descending. Python built-in functions or methods can be used to accomplish this. In this tutorial, we will cover different ways to sort a list of strings in Python.
Step 1: Create a Sample List of Strings
Before we dive into sorting, let’s create a sample list of strings that we’ll use throughout this tutorial.
1 |
string_list = ['apple', 'banana', 'cherry', 'date', 'fig', 'grape', 'kiwi', 'lemon', 'mango', 'nectarine', 'orange', 'pear', 'plum', 'raisin'] |
Step 2: Use the sort() Method
Python’s built-in method .sort
allows you to sort a list in place. This means that the original list is sorted, and you don’t need to create a new one.
Here’s how to use the sort
method:
1 |
string_list.sort() |
Now, our list will be sorted in alphabetical order.
['apple', 'banana', 'cherry', 'date', 'fig', 'grape', 'kiwi', 'lemon', 'mango', 'nectarine', 'orange', 'pear', 'plum', 'raisin']
Step 3: Sort in Reverse Order
To sort the list in reverse order (descending order), simply set the reverse
argument to True
:
1 |
string_list.sort(reverse=True) |
Our ‘string_list’ will be sorted in descending order now:
['raisin', 'plum', 'pear', 'orange', 'nectarine', 'mango', 'lemon', 'kiwi', 'grape', 'fig', 'date', 'cherry', 'banana', 'apple']
Step 4: Use the sorted() Function
Alternatively, you can use the built-in ‘sorted()’ function to create a new sorted list without modifying the original one. This is a good practice if you want to keep intact the original list and create a new one.
1 |
sorted_list = sorted(string_list) |
Here, the ‘sorted_list’ will have sorted elements of the ‘string_list’ in ascending order:
['apple', 'banana', 'cherry', 'date', 'fig', 'grape', 'kiwi', 'lemon', 'mango', 'nectarine', 'orange', 'pear', 'plum', 'raisin']
If you want to sort this list in reverse order, set the reverse
argument to True
when using the sorted()
function:
1 |
sorted_list = sorted(string_list, reverse=True) |
Our ‘sorted_list’ will now contain the elements of the ‘string_list’ in descending order:
['raisin', 'plum', 'pear', 'orange', 'nectarine', 'mango', 'lemon', 'kiwi', 'grape', 'fig', 'date', 'cherry', 'banana', 'apple']
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 |
string_list = ['apple', 'banana', 'cherry', 'date', 'fig', 'grape', 'kiwi', 'lemon', 'mango', 'nectarine', 'orange', 'pear', 'plum', 'raisin'] string_list.sort() print(string_list) string_list.sort(reverse=True) print(string_list) sorted_list = sorted(string_list) print(sorted_list) sorted_list = sorted(string_list, reverse=True) print(sorted_list) |
Conclusion
We have covered different ways to sort a list of strings in ascending and descending order using the sort()
method and the sorted()
function in Python. Now you can efficiently organize lists of strings as per your requirements.