![]() |
When working with Python programs, be it any machine learning program or simple text processing program, you might have come across a need to sort a list of strings alphabetically, either in ascending or reverse order. Strings are sorted alphabetically based on their initial letter (a-z or A-Z). But, the strings that start with uppercase characters(A-Z) come before strings that begin with lowercase characters(a-z). This means the string “Apple” will come before the string “apple” in alphabetical order, as “Apple” starts with an uppercase character. Sort the List Of Strings AlphabeticallyBelow, are the various ways to alphabetically sort a list of strings in Python.
Naive ApproachIn this example, code defines a function Python3
Output : Sorted List: ['courses', 'horje', 'hello', 'learn', 'python', 'world'] Using sort() functionThe sort() function sorts the elements of a list in ascending order by default. The sort() function sorts the list in place, meaning it will modify the original list.
Sort in Alphabetically Order : Below, given code initializes a list of strings ( Python3
Output : Original list: ['hello', 'world', 'learn', 'horje', 'courses', 'python'] Using sorted() functionThe sorted() function sorts the elements of a list passed to it in ascending order by default. The sorted() function sorts returns a new sorted list, which means it will leave the original list unchanged.
Sort in Alphabetically Order : Below code first prints the original list and then prints the sorted version of the list using the Python3
Output : Original List: ['JavaScript', 'Java', 'ReactJS', 'Flask', 'Flutter'] Use `sort()` or `sorted()` Based on Your Needs.
Both methods have their uses, and you can even use Related Article: ConclusionIn this article, we looked at two different ways of sorting a list of strings alphabetically in Python using the sort() and sorted() function with the help of examples. We also looked at using reverse=True as a parameter to sort the list of strings in reverse order. We also looked at which one is better to use when as both sort() and sorted() functions can help sort the list of strings alphabetically. |
Reffered: https://www.geeksforgeeks.org
Python Programs |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 11 |