How To Sort A List Of Strings In Python

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.

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:

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:

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.

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:

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

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.