Thanks to visit codestin.com
Credit goes to flexiple.com

Flexiple Logo
  1. Home
  2. Blogs
  3. Python
  4. How to sort list alphabetically Python?

How to sort list alphabetically Python?

Author image

Ancil Eric D'Silva

Software Developer

Published on Fri Mar 11 2022

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.

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:

letters = ["e","f","g","h","c","a","b","d"]

letters.sort()
    
print(letters)

The above code snippet outputs the following value:

['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:

letters = ["e","f","g","h","c","a","b","d"]

print(sorted(letters))
print(letters)

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.

['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.

Closing Thoughts:

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.

Related Blogs

Browse Flexiple's talent pool

Explore our network of top tech talent. Find the perfect match for your dream team.