How to sort a list of strings using list.sort() in python ?
In this article we will discuss about 4 different ways of sorting a list of strings.
In python, list is a versatile data type which stores multiple elements in a single variable without caring about the types of data.
Syntax : my_list = [element1, element2, element3]
The 4 ways are
- By Alphabetical Order
- By Reverse Alphabetical Order
- By String Length
- By Numeric Order
List provides a sort()
method by using which we can sort the elements of list from lower order to higher order.
So, let’s start exploring the topic.
Method-1 : By Alphabetical Order
Let’s see a program how it sorts in alphabetical order.
#Program : #List Of Strings my_list = ['bat' , 'ant', 'cat', 'eye', 'dog'] my_list.sort() print(my_list)
Output : ['ant' , 'bat', 'cat', 'dog', 'eye']
Method-2 : By Reverse Alphabetical Order
Let’s see a program how it sorts in alphabetical order.
#Program : #List Of Strings my_list = ['bat' , 'ant', 'cat', 'eye', 'dog'] my_list.sort(reverse=True) print(my_list)
Output : ['eye' , 'do', 'cat', 'bat', 'ant']
Here, sort() method accepts another argument reverse, and it it is True then it sorts the element. Default value is False. When set True, it sorts element in reverse order.
Method-3 : By String Length
Let’s see a program how it sorts in alphabetical order.
#Program : #List Of Strings my_list = ['apple' , 'ant', 'aeroplane', 'auto', 'a'] my_list.sort(key=len) print(my_list)
Output : ['a' , 'ant', 'auto', 'apple', 'aeroplane']
Here, sort() method accepts another argument i.e key. During sorting each element of list will be compared with each other.
Syntax : list.sort(key=function)
Here we have passed len()
function as key function. And all the element are sorted as per string length.
Method-4 : By Numeric Order
Suppose we have a list of strings, where each element are of numbers. There we can use int() as key function.
Let’s see a program how it sorts in alphabetical order.
#Program : #List Of Strings my_list = ['4' , '6', '1', '3', '2'] my_list.sort(key=int) print(my_list)
Output : ['1','2','3','4','6']