Future-Proof Your Career, Master Data Skills + AI

Blog

Future-Proof Your Career, Master Data Skills + AI

Blog

How to Sort a List Alphabetically in Python: 2 Best Methods

by | 10:15 pm EST | November 26, 2023 | Python

Sorting a list alphabetically is a standard programming task when working with data in any programming language.

So, how can you perform this task in Python?

To sort a list alphabetically in Python, you can use either the built-in sorted() function or the sort() method. Both of these methods take in a list and return them sorted in either an ascending or descending order.

In this article, we’ll provide you with an understanding of how these functions work.

We’ll also delve into some additional techniques that can be applied to customize the sorting process according to your specific needs.

So, let’s get started!

How to Sort a List Alphabetically in Python

How to Sort a List Alphabetically in Python

In Python, there are various methods you can use to sort a list alphabetically. Two of the most commonly used methods are the sort() method and the sorted() function.

We’ll look at both of them in this section:

Using the sort() Method

The sort() method is a built-in method for lists that sorts the list in place, meaning it modifies the original list directly. To use this method, simply call it on your desired list like this:

my_list = ["zucchini", "eggplant", "bell peppers", "tomato paste"]
my_list.sort()
print(my_list)

Output:

['bell peppers', 'eggplant', 'tomato paste', 'zucchini']

After executing the code, my_list will be sorted alphabetically, resulting in the output displayed. Now, the initial list is in alphabetical order.

You can also sort the list in reverse alphabetical order. All you need to do is add the reverse argument to the sort function. Here’s an example:

my_list = ["zucchini", "eggplant", "bell peppers", "tomato paste"]
my_list.sort(reverse = True)

print(my_list)

Output:

List sorted in reverse

Now, the list is sorted in the reverse order.

Using the sorted() Function

The sorted() function is a built-in function that takes an iterable such as a list as its input and returns a new list with the sorted elements, without modifying the initial list. To use this function, pass your list as an argument:

my_list = ["zucchini", "eggplant", "bell peppers", "tomato paste"]
sorted_list = sorted(my_list)
print(my_list)
print(sorted_list)

Output:

Original List and New list

The function sorts my_list and stores the sorted version in the variable sorted_list, with the original list remaining unchanged.

Both the sort() method and the sorted() function sort the elements in ascending order by default. However, you can also reverse the sorting order by using the reverse parameter:

sorted_list = sorted(my_list, reverse=True)
print(sorted_list)

Output:

['zucchini', 'tomato paste', 'eggplant', 'bell peppers']

Keep in mind that the sort() method can only be used on lists, while the sorted() function can be applied to any other iterable object like a tuple, dictionary, etc.

How to Sort a Mixed Case List Alphabetically in Python

Mixed case lists are lists that contain strings starting with both lowercase and uppercase letters. Sorting these lists with the two methods outlined in the previous section can result in errors if it’s not done right.

This is because Python sorts lists according to the ASCII value of the first letter, and in the ASCII system uppercase letters come before lowercase letters. For example:

list1 = ['car', 'Train', 'airplane', 'Submarine']
list1.sort()
print(list1)

Output:

['Submarine', 'Train', 'airplane', 'car']

The result shows that Python places the uppercase strings ahead of the lowercase ones while sorting. This results in a list that isn’t in the alphabetical order. lowercase letter one argument a z

We can solve this by using the key parameter. This parameter lets us pass in a str.lower() function, which converts all the strings to lowercase while sorting them. Let’s look at an example:

my_list = ['car', 'Train', 'airplane', 'Submarine']
my_list.sort(key=str.lower)
print(my_list)

Output:

Sorted mixed case list

Now, we can see that the list is sorted in the proper alphabetical order, irrespective of the case of the strings. If you need to sort the list in descending alphabetical order, you can pass the reverse=True parameter to the sort() method:

my_list = ['apple', 'Orange', 'Banana', 'grape']
my_list.sort(key=str.lower, reverse=True)
print(my_list)

Output:

['Orange', 'grape', 'Banana', 'apple']

Aside from the sort() method, you can also use the built-in sorted() function to sort a list alphabetically. The sorted() function returns a new sorted list, without modifying the original list. You can use the same parameters: key for case-insensitive sorting and reverse for descending order.

my_list = ['apple', 'Orange', 'Banana', 'grape']
sorted_list = sorted(my_list, key=str.lower, reverse=False)

How to Sort a Nested List Alphabetically in Python

Nested lists are lists that contain lists or any other iterable. In this section, we’ll be discussing how you can sort lists like this alphabetically.

You can sort a nested list using the normal sort() method or the sorted function. This method will sort the list alphabetically according to their first elements. For example:

list1 = [["London", "Heathrow", "Chelsea"], ["Chicago", "O'Hare", "Cubs"], ["Berlin", "Brandenburg", "Union Berlin"]]
list1.sort()
print(list1)

Output:

[['Berlin', 'Brandenburg', 'Union Berlin'], ['Chicago', "O'Hare", 'Cubs'], ['London', 'Heathrow', 'Chelsea']]

However, what happens if you want to sort the list alphabetically by another element, let’s say the third element? You can achieve this using the key parameter. Let’s take a look at this in an example:

list1 = [["London", "Heathrow", "Chelsea"], ["Chicago", "O'Hare", "Cubs"], ["Berlin", "Brandenburg", "Union Berlin"]]
list1.sort(key = lambda x:x[1])
print(list1)

Output:

Sorting list with the key parameter

In this example, we pass in a lambda function that retrieves the second element from each list in the nested list and sorts the list alphabetically using them.

Dealing with Complexities When Sorting Lists

In this section, we will discuss the complexities related to sorting a list alphabetically in Python.

Understanding these complexities helps you pick the most efficient sorting technique and write better code when dealing with large datasets.

The sort() and sorted() functions in Python perform well with reasonably sized lists.

However, as the list size increases, so does the time taken to sort it. The time complexity of these methods is approximately O(n log n).

Specifically, Python uses a variant of the Timsort algorithm, which takes advantage of sorted sub-sequences present in the input data.

Also, keep in mind that the sort() function alters the original list, while the sorted() function returns a new sorted list without affecting the original list.

This difference can affect the performance of your code in terms of memory consumption and execution time, especially in situations where hardware resources are at a premium.

Final Thoughts

Understanding how to sort lists alphabetically in Python enables you to efficiently manipulate your data.

In this article, we’ve discussed the syntax of the sort and sorted methods. We’ve also covered their various use cases and how to further manipulate them with the critical parameters.

By incorporating the discussed methods into your coding toolbox, you’ll be able to elegantly organize your data and glean useful insights from it!

Looking for some test datasets to practice with? Check out our video on How To Load Sample Datasets In Python!

Frequently Asked Questions

What is the difference between sort and sorted in Python?

The main difference between sort() and sorted() is that sort() modifies the original list in place, while sorted() returns a new list with sorted elements. For example:

names.sort()  # Modifies names in-place
sorted_names = sorted(names)  # Creates a new list without modifying names

How do I sort a list of strings in Python, ignoring case?

You can sorta list of strings, ignoring case, by providing a key argument with a lambda function that converts strings to lowercase. Example:

names = ['Alice', 'bob', 'Eve', 'charlie']
names.sort(key=lambda x: x.lower())
print(names)

Output:

['Alice', 'bob', 'charlie', 'Eve']

What’s the role of the ‘key’ argument in Python’s sorted function?

The key argument in Python’s sorted() function is used to define custom sorting criteria. You can provide a function that takes an element as input and returns a value that is used to determine the order of elements. For example:

names = ['Alice', 'Bob', 'Eve', 'Charlie']
sorted_names = sorted(names, key=len)  # Sort names by string length
print(sorted_names)

How to sort a dictionary by keys alphabetically in Python?

To sort a dictionary by its keys alphabetically, you can use the sorted() function and pass the dictionary items. Example:

my_dict = {'dog': 3, 'cat': 2, 'bird': 5}
sorted_dict = {k: v for k, v in sorted(my_dict.items())}
print(sorted_dict)

Output:

{'bird': 5, 'cat': 2, 'dog': 3}

How can I sort a set in an alphabetical order in Python?

Since sets are unordered collections, you can sort a set. However, instead of returning a set, it returns a list with the sorted elements of the set.

my_set = {'Alice', 'Bob', 'Eve', 'Charlie'}
sorted_list = sorted(my_set)
print(sorted_list)

Output:

['Alice', 'Bob', 'Charlie', 'Eve']

Related Posts