How to sort the words alphabetically in 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))
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:
You can also sort the list in reverse order by doing this:
Using sort() Function
ListName.sort() will sort it alphabetically. You can add
reverse=False/True in the brackets to reverse the order of items:
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.
IDE: PyCharm 2020.1.1 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.