How To Sort A List Alphabetically In Python

In this tutorial, we will be covering how to sort a list alphabetically in Python. Sorting data is a common task in programming and Python makes this task even simpler with its in-built functions.

Python provides a handy .sort() method that you can take advantage of to sort any list. This method changes the order of a list it is called on. Let’s delve in and see how this works.

Step 1: Starting with a Basic List

In Python, a list is a data structure that holds an ordered collection of items, which can be of any type. Here is a simple list:

We have a list called fruits containing five elements. They are not arranged in order, alphabetically.

Step 2: Using the .sort() Method

To sort the fruits list alphabetically, we just need to call the .sort() method on the list:

When you print out the list now, you will get:


The list has been sorted in ascending order, which is alphabetically in this case.

Step 3: Using sorted() Function

You can also use Python’s in-built function sorted(), which sorts the elements of a given iterable in a specific order (either ascending or descending) and returns the sorted iterable as a list:


The main difference here is that the original list is not changed when using the sorted() function. It returns a new list that is sorted, rather than sorting the existing list.

Sample Code


And there you go! Now you know how to sort a list alphabetically in Python using the .sort() method and sorted() function. These are great tools that you can use to easily sort your data in Python. Remember that .sort() modifies the list it is called on, while sorted() creates a new sorted list and leaves the original unaltered.