Python sort list (Array) Alphabetically Example | data structure

How to sort the words alphabetically in List?

Given List:-

Answer: You can use sort() or sorted() python function for sort list 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:

Output: [‘Alpha’, ‘Beta’, ‘Gama’, ‘Thor’, ‘Tony’, ‘Zuba’]

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: ListName.sort(reverse=False)

Output: [‘Alpha’, ‘Beta’, ‘Gama’, ‘Thor’, ‘Tony’, ‘Zuba’]

Learn more about the this method with example 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.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.