Python | Sorting the list by the length of the elements

Python Methods and Functions

In this program, we need to take a list and sort it by the length of the elements present inside. 
Examples:

 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) 

# Python code to sort the list by creating
# other list Using sorted ()

def Sorting (lst):

lst2 = sorted (lst, key = len )

return  lst2

 
# Driver code

lst = [ "rohan " , " amy " , "sapna" , "muhammad"

"aakash" , "raunak" , "chinmoy" ]

print (Sorting (lst))

Syntax for sorting without creating a new list:

 unsorted_list.sort (key = len) 

# Python code to sort the list without
# create another list Using sort ()

def Sorting (lst):

lst.sort (key = len )

  return lst

 
# Driver code

lst = [ "rohan" , "amy" , "sapna" , "muhammad"

"aakash" , "raunak" , " chinmoy " ]

print (Sorting ( lst))

Output:

 ['amy',' rohan', 'sapna',' aakash', 'raunak',' chinmoy', 'muhammad'] 

Works:
This a key Python feature when implementing sorting is called the decorate-sort-undecorate theme. The following steps follow:

  1. Each list item is temporarily replaced with a "styled" version that includes the result of the key function applied to the item.
  2. The list is sorted based on the natural order of the keys .
  3. Decorated elements replaced with original elements.


Link:
stackoverflow





Tutorials