In this program, we need to take a list and sort it by the length of the elements present inside.
Input: list = ["rohan", "amy", "sapna", "muhammad", "aakash", "raunak", "chinmoy"] Output: [' amy', 'rohan',' sapna', 'aakash',' raunak', 'chinmoy',' muhammad'] Input: list = [["ram", "mohan", "aman"], ["gaurav" ], ["amy", "sima", "ankita", "rinku"]] Output: [['gaurav'], [' ram', 'mohan',' aman'], ['amy',' sima ',' ankita', 'rinku']] Note: The first example comprises of Strings whose length can be calculated. The second example comprises of sublists, which is also arranged according to there length.
There are many ways to do this. Anyone can use their own algorithmic technique, but Python provides us with various built-in functions to execute them. Built-in functions include sort () and sorted () along with the key parameter. We can accomplish this in two ways. One way is to sort the list by creating a new list, and another way is to sort on the given list, saving space.
Syntax for sorting by creating a new list:
sorted_list = sorted (unsorted_list, key = len)
Syntax for sorting without creating a new list:
unsorted_list.sort (key = len)
['amy',' rohan', 'sapna',' aakash', 'raunak',' chinmoy', 'muhammad']
This a key Python feature when implementing sorting is called the decorate-sort-undecorate theme. The following steps follow: