How to sort the words alphabetically in List?
Given List:-
['Zuba', 'Alpha', 'Beta', 'Thor', 'Gama', 'Tony']
Answer: You can use the sort() or sorted() python function for sort lists alphabetically in python.
- sort() function – will modify the list it is called on.
- sorted() function- will create a new list containing a sorted version of the list it is given
Example of sort list alphabetically in Python
Using sorted() Function
If you have a list of strings. You can sort it like this:
list1 = [‘Zuba’, ‘Alpha’, ‘Beta’, ‘Thor’, ‘Gama’, ‘Tony’]print(sorted(list1))Output:
Note: If words that start with an uppercase letter get preference over those starting with a lowercase letter. If you want to sort them independently, do this:
sorted(list, key=str.lower)
You can also sort the list in reverse order by doing this:
sorted(lst, reverse=True)
Using sort() Function
ListName.sort()
will sort it alphabetically. You can add reverse=False/True
in the brackets to reverse the order of items: ListName.sort(reverse=False)
list1 = ['Zuba', 'Alpha', 'Beta', 'Thor', 'Gama', 'Tony'] list1.sort() print(list1)
Output: [‘Alpha’, ‘Beta’, ‘Gama’, ‘Thor’, ‘Tony’, ‘Zuba’]
Learn more about this method with examples and Important points:- Python sort() list (Array) function
Do comment if you have any doubts and suggestions on this tutorial.
Note:
IDE: PyCharm 2020.1.1 (Community Edition)
macOS 10.15.4
Python 3.7
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.