The list is one of the Python data structures with a mutable property. The list can absorb the data of any format and enclose them within the “square brackets [ ]”. The “mutable” property of the list allows the list to sort the data alphabetically in ascending or descending order or sort the data by accessing the particular index element. Sorting a list alphabetically may be needed in use cases like sorting the names in the mobile contact list, or sorting integer value. In all such scenarios, the list sorting applies to any type of data either “string”, “tuple”, or “number”, and so on.
This article will demonstrate sorting a list alphabetically in Python. It will cover the below-highlighted concepts with examples:
- How to Sort a List Alphabetically in Python?
- Approach 1: Using the “sort()” and “sorted()” Functions to Sort a List Alphabetically in Python
- Approach 2: Using the Bubble Sorting Approach to Sort a List Alphabetically in Python
How to Sort a List Alphabetically in Python?
To sort a list alphabetically in Python use the “sort()” or the “sorted()” function. Bubble sorting is another prevalent approach to sorting the list alphabetically.
For demonstration follow the below set of approaches:
Approach 1: Using the “sort()” and “sorted()” Functions to Sort a List Alphabetically in Python
Below are detailed demonstrations of alphabetical list sorting in Python with comparative examples using the “sort()” and “sorted()” functions:
Use Case 1: Sorting List Alphabetically Using Sort() Function
The sort() function sorts the list alphabetically by default, however, depending on the scenario the alphabetical sorting sequence of the list can be re-sorted in any other sequence, such as ascending or descending.
To sort a list alphabetically in Python, use the sort() method with the “list” using the “dot(.)” notation. The “dot” notation gives flexibility to the “list” to access the “sort()” method to perform the alphabetical sorting operation on the sequence.
Here’s how you can sort a list alphabetically in Python using the “sort()” approach:
indoor_plants = ['Pothos', 'Philodendron', 'Money Tree', 'Chinese Evergreen', "Jade Plant"]
indoor_plants.sort()
print("Sort List Alphabetically:\n ", indoor_plants)
Output
List Sorting Alphabetically Using Sorted() Function
To sort the list alphabetically using the sorted() function, you need to specify the list with the “()” braces of the function. Here’s how you can implement the “sorted()” function using the example:
indoor_plants = ['Pothos', 'Philodendron', 'Money Tree', 'Chinese Evergreen', 'Jade Plant']
print("Sort List Alphabetically:\n ", sorted(indoor_plants))
Output
Use Case 2: List Sorting Alphabetically Using Sort() Function by Considering the Reverse Parameter
However, sometimes programmers are interested in sorting the contact numbers by the person’s name alphabetically but in descending order. In such scenarios, where you want to sort a list alphabetically according to the required need, then use the “sort()” with the function parameter “reverse”. The “reverse” parameter will sort the list alphabetically in ascending order by default and by default it is set to “False”.
However, to manually sort the list in descending order alphabetically, you need to specify the “reverse” parameter set to “True”. It will reverse the sequence by placing the largest element to the rightmost of the list.
Here’s how you can sort a list alphabetically by considering the “reverse” parameter of the sort() function:
indoorplants = ['Pothos', 'Philodendron', 'Money Tree', 'Chinese Evergreen', "Jade Plant"]
indoorplants.sort(reverse=True)
print("Sort List Alphabetically:\n ", indoorplants)
Output
List Sorting Alphabetically Using Sorted() Function by Considering the Reverse Parameter
The sorted() function will sort a list alphabetically in reverse order by specifying the “reverse” parameter to “True”. The reverse order of the list means that it will sort the list in descending order. As by default the “sorted()” function returns the list in ascending order.
Here’s how you can implement the alphabetical reverse sorting of the list:
ide= [('Anaconda', 3, 'Python_ide'),('PyCharm', 3, 'Python Programming'), ('Jupyter notebook', 3, 'iPython'),]
print("\nSort List by considering:\n ", sorted(ide, reverse=True))
Output
Use Case 3: Alphabetically Sorting a List of Tuples Using “sort()” Function
If you have data in the form of tuples, you can sort them alphabetically by converting them to a list using the “List” built-in data type in Python. However, if you have a list containing data in tuples, you can sort them by using the “sort()” function. Here’s how you can sort the list of tuples using the “sort()” function alphabetically:
plants_inventory = [('pothos', 30),
('Philodendron', 40),
('Jade Plant', 50)]
plants_inventory.sort(reverse=False)
print("Sort List Alphabetically:\n ", plants_inventory)
Output
Alphabetically Sorting a List of Tuples Using “sorted()” Function
To sort a list of tuples alphabetically, use the “sorted()” function. The “reverse” parameter is set to “False” to print the elements in descending order. Here’s how you can implement, the sorted() operation of the list of tuples:
plants_inventory = [('pothos', 30), ('Jade Plant', 50), ('Philodendron', 40)]
print("Sort List Alphabetically:\n ", sorted(plants_inventory, reverse=False))
Output
Use Case 4: Alphabetically Sorting a List of Integers Using “sort()” Function
To sort a list of numbers in Python, use the sort() function. Here in the below example, the list contains a real number (can either be positive, negative, or both), and the sort() operation is utilized to sort the sequence of integers in descending order by specifying the sort() parameter “reverse” to “True”:
corona_cases = [3,8,16,50, 150, 300, 500, 1000]
corona_cases.sort(reverse=True)
print("Sort List Alphabetically:\n ", corona_cases)
Output
Alphabetically Sorting a List of Integers Using “sorted()” Function
The sorted() function is used to sort the list of integers in ascending order. The list is called within the parentheses “()” of the sorted() function to traverse the list elements in a particular order. Here’s how you can implement the “sorted()” function operation on the list of real numbers:
corona_cases = [3,8,16, 150, 50, 500, 300, 1000]
print("Sort List Alphabetically:\n ", sorted(corona_cases))
Output
Use Case 5: Alphabetically Sorting a List Using the “sort()” Function by Considering the Index Location
To sort a list alphabetically in Python, you need to specify the user-defined function with the return statement. Within a return statement specify the index of element for which you want the list to be sorted. Then, using the “key” parameter of the “sort()” function, sort the list elements alphabetically but considering the index location of a particular element in a list of tuples.
Here’s how you can implement the “index” sorting operation using the “sort()” function:
plants_inventory = [('pothos', 30),
('Philodendron', 40),
('Jade Plant', 50)]
# define a sort key
def Alphabetically_sort_key(plants_inventory):
return plants_inventory[1]
# sort the companies by revenue
plants_inventory.sort(key=Alphabetically_sort_key, reverse=True)
# show the sorted companies
print("Sort List Alphabetically:\n ", plants_inventory)
Output
Alphabetically Sorting a List Using the “sorted()” Function by Considering the Index Location
The above results can be acquired by implementing the “sorted()” results. In the below example, the tuple contains the “integer” value as a second index element. So, the sorted() function sorts the list of tuples in ascending order by considering the second element in the index:
plants_inventory = [('Philodendron', 40), ('Jade Plant', 50), ('pothos', 30)]
# define a sort key
def Alphabetically_sort_key(plants_inventory):
return plants_inventory[1]
# sort the companies by revenue
plants_inventory.sort(key=Alphabetically_sort_key, reverse=False)
# show the sorted companies
print("Sort List Alphabetically:\n ", plants_inventory)
Output
Use Case 6: Alphabetically Sorting a List Using the Lambda Function
Another practice is to sort a list alphabetically and utilize the “key” parameter within it using the “lambda” operation. The “lambda” will take a single argument and return the item at a particular index “i[1]”. The “lambda i: i[1]” operation will target the “first” element from the list that is at index “1” (remember index count starts from “0”). The “sort()” function will sort the list of tuples index-wise in ascending order (from lower to higher value):
plants_inventory = [('Philodendron', 40), ('Jade Plant', 50), ('pothos', 30)]
# sort the companies by revenue
plants_inventory.sort(key=lambda i: i[1])
# show the sorted companies
print("Sort List Alphabetically:\n ", plants_inventory)
Output
Alphabetically Sorting a List Using the Lambda Function
To sort a list alphabetically index-wise, use the “lambda” function to grab the particular element from the lists of tuples. Here’s how you can grab the second element from the list and sort them alphabetically using the “sorted()” function:
ide = [('Anaconda', 'Jupyter notebook', 'iPython'), ( 'PyCharm', 'Spyder', 'Programming')]
idenames_sorting_item = sorted(ide, key=lambda i: i[2])
print("\nSort List by considering first item:\n ", idenames_sorting_item)
Output
Use Case 7: Alphabetically Sorting a List by Considering the Lowercase
To sort the list of strings based on their capitalization utilize the “str” built-in data type with the supported “lower” attribute using the “dot(.)” operator. However, specify this operation in the “key” parameter of the sort() function.
Here’s how you can change the order of the list by considering the lower elements in alphabetical order:
ide = ['Anaconda', 'Jupyter notebook', 'iPython', 'PyCharm','Spyder']
ide.sort(key=str.lower)
print("Sort List Alphabetically:\n ", ide)
Output
Alphabetically Sorting a List by Considering the Lowercase
To achieve the above results use can utilize the “sorted()” function. To do so, within the sorted() function consider the two arguments. The first argument is the list and the second argument is the “key” parameter. Within the key parameter specify the “str” to handle the string characters and the “lower” attribute to access the string in the list:
ide = ['Anaconda', 'Jupyter notebook', 'iPython', 'PyCharm','Spyder']
idenames = sorted(ide, key=str.lower)
print("Sort List Alphabetically:\n ", idenames)
Output
Approach 2: Use the Bubble Sorting Approach to Sort a List Alphabetically in Python
The “bubble sorting” is required where you are interested in arranging the same sequence in a particular order (either ascending or descending). Its algorithm works on the idea of swapping the adjacent elements in the sequence. The “swapping” is achieved by iterating over the number of definite iterations through looping. The elements of the sequence are swapped over one another to get the desired output.
Here’s how you can sort a list alphabetically in Python through the bubble sorting approach:
string = "Bubble Sorting Alphabetically"
print("\nOriginal String =",string)
#convert list to string
list = string.split(" ")
# iterate over each element in the list
for w in range(len(list)):
# convert all words to lowercase
list[w]=list[w].lower()
# Bubble sort to sort the words
for n in range(len(list)-1, 0, -1):
for i in range(n):
if list[i] > list[i + 1]:
# swapping
list[i], list[i + 1] = list[i + 1], list[i]
print("\nSorted string Alphabetically =",list)
The outer “for…in” structure checks the “elements” in the list to decide how many iterations are required to sort a list. Besides that lowercase each string if capitalized. However, the inner “for…in” loop structure executes the swapping operation of each element. Inside, it is another “for…in” structure that compares the adjacent elements using the comparison operator “>”. The assignment operator “=” will update the list by assigning the new alphabetical order position to the element and overwrite the previous element through adjacent swapping:
Output
That is all about sorting a list alphabetically in Python.
Conclusion
To sort a list alphabetically in Python, use the “sort()” or “sorted()” function. However, to sort a list alphabetically in the reverse(descending) order specify the “reverse=True” within the sort function braces “()”. To sort the list according to the lowercase scenario, use the “key” parameter of the sorted function and utilize the “str” with the “lower” attribute using “dot(.)” notation. This article has demonstrated the use cases and examples to sort a list alphabetically in Python.