Greetings, Python Holics! We know that alphabetizing a list is a common task that every programmer should know in python. In this article, we will learn how to sort a list alphabetically in python with different methods.
How to Sort a List alphabetically in python?
Being able to sort/organize your data in an ordered sequence is a required skill when working on massive datasets. Sorting your data can even assist you to optimise your method and reducing the complexity of your code. It becomes more important when you are working on a government or organization project.
Let's see a few ways to alphabetize a list in python:
Method 1) Sorted() Function
The sorted() function is a built-in function in python that takes any iterable like a list and returns a new sort list, that will be alphabetically sorted for a list of strings. It can be done for both increasing and decreasing orders. But note that you can’t sort combined lists of numeric and alphabets.
Example:
str= ("python", "java", "tutoring", "Favtutor", "Machine Learning", "Studies", "Code", "Students") x = sorted(str, reverse=False) print(x)
Output:
['Code', 'Favtutor', 'Machine Learning', 'Students', 'Studies', 'java', 'python', 'tutoring']
To do this in descending order, we will use the Reverse as a hyperparameter for the order by which you want to sort your list, False is ascending and True is descending.
Example:
str= ("python", "java", "tutoring", "Favtutor", "Machine Learning", "Studies", "Code", "Students","Zebra","apple") x = sorted(str, reverse=False) print(x)
Output:
['Code', 'Favtutor', 'Machine Learning', 'Students', 'Studies', 'Zebra', 'apple', 'java', 'python', 'tutoring']
In the above output, you may be wondering why Zebra is placed before apple in the sorted list. This is because 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.
But what if we want to sort the original list in place, you can use the sort() method instead.
Method 2) sort() function
The sort function alters the initial list in alphabetical order. No arguments are supplied inside this function. So, when using this method on crucial or priceless data, keep in mind that it overwrites your data and prevents you from retrieving the original after the function has been completed.
An advantage of the sort() function is that it is a space-efficient algorithm that uses the least amount of hardware resources to complete the work since it sorts in place, that is, without the need for additional space. Data is incrementally converted on-site. Updating the input prevents the need for double the storage.
Example:
str= ["python", "java", "tutoring", "Favtutor", "Machine Learning", "Studies", "Code", "Students","Zebra","apple"] str.sort() print(str)
Output:
['Code', 'Favtutor', 'Machine Learning', 'Students', 'Studies', 'Zebra', 'apple', 'java', 'python', 'tutoring']
These two methods are also great for sorting tuples in python. It can also improve the efficiency of searching for elements in tuples.
Method 3) Using a key
As we have already seen, the two functions sorted() and sort() give uppercase strings precedence over lowercase ones. We could want to sort without regard to the case.
Setting the key argument to str.lower will accomplish this. You will require a function or other callable that accepts one argument and returns a sorting key in order to utilize this style of sorting on your data. This is because the key function is only called once for each input, this strategy is quick.
Example:
s= ["python", "java", "tutoring", "Favtutor", "Machine Learning", "Studies", "Code", "Students","Zebra","apple"] lower_string=[i.lower() for i in s] s.sort() print("using sort function","\n",s) print("---------------------------------------------------------") x = sorted(s, reverse=False) print("using sorted function","\n",x)
Output:
using sort function ['Code', 'Favtutor', 'Machine Learning', 'Students', 'Studies', 'Zebra', 'apple', 'java', 'python', 'tutoring'] --------------------------------------------------------- using sorted function ['Code', 'Favtutor', 'Machine Learning', 'Students', 'Studies', 'Zebra', 'apple', 'java', 'python', 'tutoring']
Method 4) Without using any function
There are some situations where you need to know some simple alternative ways without using a built-in method. Let's see how to sort a list alphabetically in Python without the sort function.
We can use any popular sorting techniques like quick sort, bubble sort, or insertion sort to do it. Let's learn how to do it with Quick sort, which can be two to three times faster. The algorithm's foundation is Pivot values, which are frequently implemented recursively. When a pivot is present, everything to the left of the pivot is always smaller, and everything to the right is always larger.
Example:
def sort(lst): if not lst: return [] return (sort([x for x in lst[1:] if x < lst[0]]) + [lst[0]] + sort([x for x in lst[1:] if x >= lst[0]])) s= ["python", "java", "tutoring", "Favtutor", "Machine Learning", "Studies", "Code", "Students","Zebra","apple"] print(sort(s))
Output:
['Code', 'Favtutor', 'Machine Learning', 'Students', 'Studies', 'Zebra', 'apple', 'java', 'python', 'tutoring']
Conclusion
Today we discussed sorting a list in alphabetical order using various methods in python with code. But remember that a stable sorting algorithm must maintain the comparative elements' original relative order in order to be taken into account. Happy Learning :)