How to sort list alphabetically Python?
In this short tutorial, we look at how to sort list alphabetically in Python. We look at the various methods and discuss their use cases.
Table of Contents
How to sort lists alphabetically in Python?
Lists are used to store a collection of items and quite often it may contain data in an unpredictable order. This could largely be due to the order they have been added by the user. Due to this, when it comes to user input data there is no way they can be ordered. Hence it is important to have a couple of methods that can be used to sort a list.
Lists can be sorted using two methods, the sort() and the sorted() method. The former permanently sorts the list whereas sorted() is used to sort the list temporarily.
Let us take a closer look at both the methods below.
Using the sort() method:
As aforementioned, the sort() method can be used to sort a list alphabetically in Python. However, this method permanently changes the order of the items in the list. In practice use cases this might not be a problem, however, while dealing with real-world data there might be instances where the order of the list must be preserved.
Code & Explanation:
The above code snippet outputs the following value:
letters = ["e","f","g","h","c","a","b","d"] letters.sort() print(letters)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
As you can see we have used sort() to sort the list in alphabetical order in Python. We then print the original list and the values have been changed permanently.
Using the sorted() method:
In case you want to sort the list alphabetically in Python but want to preserve the original list, the sorted() method can be used. This method sorts and displays the list but does not change the original list.
Code and Explanation:
As you can see in the above code snippet, we have first sorted and printed the list after which we have printed the original list and this is the output.
letters = ["e","f","g","h","c","a","b","d"] print(sorted(letters)) print(letters)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] ['e', 'f', 'g', 'h', 'c', 'a', 'b', 'd']
As you can see here, the list was sorted but the original list was not affected.
We have covered two methods to sort a list and discussed their use cases. Although our examples use alphabets, they can be used to sort lists based on numbers as well.
As a next step, I would recommend trying to sort an alphabetical list containing items in various cases.