- How to Sort a List Alphabetically in Python
- A Brief Example of Sorting in Python
- Sort a List Alphabetically in Python with sort()
- Sort a List Alphabetically in Python with sorted()
- Sort a List Alphabetically in Python with key
- The Stability of Python’s Sorting Algorithms
- Ready to Practice Sorting in Python?
- Python Sorted By Name [duplicate]
How to Sort a List Alphabetically 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
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.
Python Sorted By Name [duplicate]
It is sorting by alphabetical order, so you need to break up the numbers and convert them to ints and sort with that. (Numbers in strings are treated as just characters, so it «sees» «A10» and tries to sort it first by «A», then by «1», and then by «0.») For example:
>>> sorted(dir, key=lambda x: int(x[1:])) ['A1', 'A2', 'A3', 'A10']
If you are going to have other letters besides «A» in dir , you’ll need a more complicated sorting method, but it will be something along the same lines. (If you explain what dir contains more, I can write an example for that.) As mgilson’s comment points out, if the elements of dir follow the 1 char + number format, then you could take advantage of tuple sorting and do something like this:
>>> dir.append('B12') >>> sorted(dir, key=lambda x: (x[0],int(x[1:]))) ['A1', 'A2', 'A3', 'A10', 'B12']
To extend this question, I had to sort interface names in a natural way. What makes it a bit more complex is interfaces can go in many flavors. You have the traditional ones such as lo , eth0 , etc. and some more advanced schemes like enp4s0f1d1 . The solution is to split them based on type, convert numbers to int’s and care must be taken to ensure comparison happens on same type.
So I came up with this sort function which should be fairly bulletproof (as long as you give it strings. )
def ethkey(eth): """Split an ethernet device name between text and digit groups as int, allowing consistent sorting of interfaces. Usage: `sorted(if_list, key=ethkey)` :param eth: Value to sort :type eth: str :return: List of str's (even indexes) and int's (odd indexes) to compare :rtype: list """ keys = [] if not eth: # If eth is a string it's empty, just return blank list return keys # Start with the first character already in last last, eth = eth[0], eth[1:] # If last is int we start at offset 1 if last.isdigit(): keys.append('') for i in eth: if i.isdigit() is last.isdigit(): # Keep accumulating same type chars last += i else: # Save and restart next round keys.append(int(last) if last.isdigit() else last) last = i # Save final round and return keys.append(int(last) if last.isdigit() else last) return keys
It can then be used as such: