How to Sort an List by String Length in Python
In this tutorial, we will learn about how to sort an list of strings according to its string length in Python.
Consider, we have the following list of strings in Python:
aList = ["John", "Ram", "Joseph", "Peter"]
To sort the list by its string length, we can use the list.sort() method by passing key=len function as an argument.
Here is an example:
aList = ["John", "Ram", "Joseph", "Peter"]
aList.sort(key=len)
print(aList)
Output:
['Ram', 'John', 'Peter', 'Joseph']
In the code above, we have passed the key=len
function as an argument to the sort() method. So, that it sorts the list based on the length of a string, by default the sort() method sorts the list in a ascending order.
If you want to sort a python list in a descending order, you can pass the reverse=True as a second argument to the sort() method.
Here is an example:
aList = ["John", "Ram", "Joseph", "Peter"]
aList.sort(key=len, reverse=True)
print(aList)
Output:
['Joseph', 'Peter', 'John', 'Ram']
Using the sorted() function
Similarly, we can also sort the python list by it’s string length using the sorted() function in python.
Here is an example:
aList = ["John", "Ram", "Joseph", "Peter"]
sortedList = sorted(aList, key=len)
print(sortedList)
Output:
['Ram', 'John', 'Peter', 'Joseph']
The sorted() takes the two arguments, the first argument is list we need to sort and the second argument is the sorting criteria function. So that it sorts the list based on the mentioned criteria.