Sort Words in a List in Alphabetical Order in Python
In this tutorial, we will learn how to sort words in a list in alphabetical order in python. This is a very simple code and requires the use of only one string function.
Python concepts used are:
list.sort()
In python, list has a member function sort(). It sorts the elements in the list in ascending order (low to high).
If the list is of numbers then list.sort() sorts the numbers in increasing order of there values.
If the list is of strings or words then list.sort() sorts the strings in dictionary order, i.e. alphabetically from low to high.
Sorting list in dictionary order
Suppose we have an input list:
str = [ 'bat', 'cat', 'hi', 'car', 'apple', 'computer' ]
We will now sort this list lexicographically (alphabetical order). We will use list.sort() command to sort the list. The sorted list will overwrite the unsorted list in the str variable.
# input list str = [ 'bat', 'cat', 'hi', 'car', 'apple', 'computer' ] str.sort() # displaying the sorted list print(str)
Here, str.sort() sorts the list str in alphabetical order. Then we are displaying the sorted string.
Output:
['apple', 'bat', 'car', 'cat', 'computer', 'hi']
So, here it is. A very simple code to sort words in a list in alphabetical order.
Also read,
- Methods to Sort list using sort() in Python
- Reverse string without using function in Python
- How to Sort words in a sentence in alphabetical order
nice thanks this is a very good tutorial and it helped with my homework