# How to Sort a List Alphabetically in Python

What if you have a list of strings (text items) and you need to sort them alphabetically? In this article, we’ll show you how to sort a list in Python.

A sorting algorithm puts elements of a list into a particular order. They help reduce the complexity of a problem and can even optimize other algorithms.

Because of its complexity, sorting is one of the most important problems in computer science. In a nutshell, sorting can be defined as arranging items in an ordered sequence. Even though the idea of sorting algorithms looks simple at first, it’s not; research into it started 70 years ago.

Writing a good sorting function on your own is not easy. Luckily, Python comes with built-in sorting functions. This article will explore how to use `sort()` and `sorted()` to sort alphabetically in Python.

## A Brief Example of Sorting in Python

Sorting algorithms have a wide range of applications. For example, government organizations, commercial enterprises, and financial institutions all organize their data by sorting it. Storing sorted data makes it easier for algorithms to search it later.

So, how exactly can you sort a list in alphabetical order in Python? Let’s look at a quick example.

Note:  If you do not know what a list is and why it is a very important Python data structure, check out our article Python Lists, Tuples, and Sets. You might also want to refer to Python Terms Beginners Should Know Part 1 and Part 2 for more information. Finally, I encourage you to enroll in our interactive Python Data Structure course so you can practice these new skills.

Back to Python sorting. Here’s the code for a simple sort:

```>>> mylist = ["world", "LearnPython.com", "pineapple", "bicycle"]
>>> sorted_list = sorted(mylist)
>>> print(sorted_list)
['LearnPython.com', 'bicycle', 'pineapple', 'world']
```

Above, the list `mylist` holds the strings “world”, “LearnPython.com”, “pineapple”, and “bicycle” in no particular order. We want to sort this list and store it as a new variable called `sorted_list`. In Python, sorting a list alphabetically is as easy as passing a list of strings to the `sorted()` method. Strings are sorted in alphabetical order based on their first letter (A-Z). However, words that start with uppercase letters come before words that start with lowercase letters. (Note: This means “Zebra” will be listed before “apple” because “Zebra” starts with a capital letter.)

Now that we understand what sorting is, we can get started with the code!

## Sort a List Alphabetically in Python with sort()

First, let’s sort a list alphabetically in Python with the `sort()` method. By default, `sort()` will place the items in ascending (A–Z) order.

Let’s take the same list as before:

```>>> mylist = ["world", "LearnPython.com", "pineapple", "bicycle"]
>>> mylist.sort()
>>> print(mylist)
['LearnPython.com', 'bicycle', 'pineapple', 'world']
```

However, note that the `sort()` method will directly modify the initial list of items and that it will not be possible to undo any changes.

If you want to sort the items in descending (Z–A) order, you can do it by setting the reverse parameter  in `sort()` as `True` or `False`.

```>>> mylist = ["world", "LearnPython.com", "pineapple", "bicycle"]
>>> mylist.sort(reverse=True)
>>> print(mylist)
['world', 'pineapple', 'bicycle', 'LearnPython.com']
```

And here we go! `mylist` is now sorted in descending order.

It is important to note that the `sort()` function sorts in place, i.e. without any additional space requirement. According to Wikipedia:

An in-place algorithm transforms input data without the need for auxiliary structures.

The idea behind an in-place algorithm is space efficiency. In other words, we want to use the minimum of hardware resources to complete the task. Essentially, the output is produced in the same memory space that holds the input; the data is successively transformed in place. This avoids using twice the storage by keeping a copy of the input.

So, should you use sort()?

If you are working with important data and there is even a possibility that you will need to retrieve the original data in the future, then `sort()` is not the best option because it modifies the original list.

On the other hand, if the data is a copy or unimportant working data, then `sort()` can be a good option. Another option is to use `sorted()` instead.

## Sort a List Alphabetically in Python with sorted()

Python also has the function `sorted()`, which we used in the opening example. Contrary to `sort()`,  this method does not modify the original list; it returns a new list with the same content as the original list but in alphabetic order. For example:

```>>> new_list = ["Python", "welcome", "hello", "programming", "sorting", "zebra", "alligator"]
>>> sort_newlist = sorted(new_list)
>>> print(sort_newlist)
['Python', 'alligator', 'hello', 'programming', 'sorting', 'welcome', 'zebra']
```

Here, the sorted `new_list` is stored in a variable called `sort_newlist`. We can always access the `new_list` variable.

Similar to `sort()`, `sorted()` also has a `reverse` argument that’s False by default. Let's set it to `True` to rearrange `new_list` in descending order:

```>>> new_list = ["Python", "welcome", "hello", "programming", "sorting", "zebra", "alligator"]
>>> sort_newlist = sorted(new_list, reverse=True)
>>> print(sort_newlist)
['zebra', 'welcome', 'sorting', 'programming', 'hello', 'alligator', 'Python']
```

## Sort a List Alphabetically in Python with key

By default `sort()` and `sorted()` use the comparison operator `<`. You can modify the order used when sorting by specifying the key argument.

Previously, we saw that `sort()` and `sorted()` prioritize uppercase strings. However, we might want case-insensitive sorting. This can be done by setting the key argument to `str.lower` (which converts all strings to lowercase characters). To use this type of sorting on your data, you will need a function or any other callable that takes one argument and returns a key used for sorting. This technique is fast because the key function is called only once for each input.

```>>> mylist = ["world", "LearnPython.com", "pineapple", "bicycle", "Anaconda", "Jupyter"]
>>> mylist.sort(key=str.lower)
>>> print(mylist)
['Anaconda', 'bicycle', 'Jupyter', 'LearnPython.com', 'pineapple', 'world']
```

And similarly with `sorted()`:

```>>> mylist = ["world", "LearnPython.com", "pineapple", "bicycle", "Anaconda", "Jupyter"]
>>> sort_mylist = sorted(mylist, key=str.lower)
>>> print(sort_mylist)
['Anaconda', 'bicycle', 'Jupyter', 'LearnPython.com', 'pineapple', 'world']
```

We can also use a custom `lambda` function as the key argument. Let’s say, I have a list of tuples that contain people’s names, occupation, and location. We want to sort them in ascending order based on each tuple’s second item. This can be done with a custom `lambda` function:

```>>> people = [('Anna', 'New York', 'Data Analyst'),('Chris', 'Berlin', 'Software Developer'),('Nancy', 'Toronto', 'Data Scientist')]
>>> sorted_people = sorted(people, key=lambda x: x[1])
>>> print(sorted_people)
[('Chris', 'Berlin', 'Software Developer'), ('Anna', 'New York', 'Data Analyst'), ('Nancy', 'Toronto', 'Data Scientist')]
```

The output is a list sorted alphabetically based on the city because `x[1]` accesses the second item of the tuple (i.e. the city name). You can learn more about how to do lambda sorts in Python in my previous article on custom sort functions.

Let’s look at the example above, but this time with `sort()`:

```>>> people = [('Anna', 'New York', 'Data Analyst'),('Chris', 'Berlin', 'Software Developer'),('Nancy', 'Toronto', 'Data Scientist')]
>>> people.sort(key=lambda x: x[1])
>>> print(people)
[('Chris', 'Berlin', 'Software Developer'), ('Anna', 'New York', 'Data Analyst'), ('Nancy', 'Toronto', 'Data Scientist')]
```

The result is the same, but we do not have access to the original people list anymore.

## The Stability of Python’s Sorting Algorithms

Finally, `sort()` and `sorted()` are guaranteed to be stable. Stable sorting means that two objects with identical keys appear in the same order in the sorted output as they do in the original input. In other words, a stable sort ensures that the original order of data with the same rank is retained in the output.

The stability of a sorting algorithm allows the possibility of multiple different correctly-sorted versions of the original list.

Stable sorting algorithms are essential for maintaining the order of equal elements. To be considered as such, they should not change the relative order of elements that are compared. This helps with sorting, for example, if we need to do it in multiple passes (like sorting by city and profession) or something like that.

On the other hand, a non-stable sort could shuffle one element while sorting by another. In this case, sorting by city could shuffle the name order, resulting in a list where the people are sorted by the city but within a city they are not sorted by name, even though they originally were sorted by name.

This is especially important when you’re dealing with more complex lists. For example, you can have a list of tuples with a string as the first element. You can sort the list alphabetically by the first argument, but the original order for the second argument of each tuple is preserved.

## Ready to Practice Sorting in Python?

This article explored how to sort a list alphabetically in Python. We discovered how to use `sort() and sorted()` to sort in Python and how they differ from each other. We also briefly covered the stability of sort algorithms in Python.

Now that you have a solid knowledge about sorting in Python, go ahead and implement your own solutions by playing with the code snippets above.

Finally, do not forget to check our interactive Built-In Algorithms in Python course. It gives you solid, hands-on practice in programming with Python. You can also visit LearnPython.com to learn more about our Python courses.