Python program to arrange names in alphabetical order

Hello Coder! In this article, we will be learning to arrange names in alphabetical order in Python. We use the sort() inbuilt method of List Data Structure to arrange names in alphabetical order.

Sort a list in Python

We make use of the inbuilt sort() method to sort a list in Python.
In Python list.sort() sorts the list in place. We can also use the sorted() function which returns the sorted list.

Syntax: sort(*, key=None, reverse=False)

The sort method takes two keyword-only arguments. The arguments are key and reverse. The key argument is used to specify a function. Key values are calculated by the function with the elements in the list as an argument to the function. By default, the key is set to None and the list is sorted without calculating the separate key values.

The reverse argument when set to True will sort the list in descending order.

Arrange names in alphabetical order in Python

Let us prompt the user to enter the number of names and declare a list list_of_names to store the names in it.

n=int(input())
list_of_names=[]

Now, let us prompt the user to enter the names. Append the names to the list_of_names.

for i in range(n):
    list_of_names.append(input())

Use the default sort() method to sort the list. By default, the list will be sorted in Alphabetical order.

list_of_names.sort()

Now, print the names in the list by iterating over list_of_names using a for loop.

for name in list_of_names:
    print(name)

Input

12
Phoenix Franco
Reuben Norton
Everett Soto
Laila Powers
Scarlett Serrano
Kasey Maynard
Deandre Palmer
Alexa Anderson
Finley Hayes
Samantha Maxwell
Randall Bean
Micah Hampton

Output

Alexa Anderson
Deandre Palmer
Everett Soto
Finley Hayes
Kasey Maynard
Laila Powers
Micah Hampton
Phoenix Franco
Randall Bean
Reuben Norton
Samantha Maxwell
Scarlett Serrano

In the output, we can notice that the names are printed in Alphabetical order.

Yahoo! In this article we have learned to sort names in alphabetical order in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *