How to sort elements of a list by length in Python

This tutorial will show you how to sort the list elements by their length in Python. Unlike arrays, lists are containers that can store the data of various data types altogether. The sorting by lengths means the sorting criteria is only the length of the elements. This can be easily done using the sorted method in python.

sorted( ) method in Python

sorted(iterable,key=key,reverse=reverse) is the python function that sorts the given collection according to a given key. It takes three arguments. The iterables are the collections through which you can iterate like list, array, set, etc. The key is the function that decides the order of sorting. For eg. length  The default value of a key is none. The reverse is a boolean value that sorts the collection in descending order if True and in ascending order if False. The default value of reverse is False.

Now define the list and sort it using this function by taking the length of elements as a key and print the result.

Python code: sort elements of a list by items’ length

#sample list
list = ["pen", "pencil", "book", "compass", "table", "notebook"]
#sort the list by the length of each element
sorted_list = sorted(list, key=len)
#print the sorted list
print(sorted_list)

Output:

["pen", "book", "table", "pencil", "compass", "notebook"]

Also, refer to Python Program to Sort an array of String according frequency

Leave a Reply

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