# Python – Sort a List according to the Length of the Elements

## Python | Sort a List according to the Length of the Elements

In this program, we need to accept a list and sort it based on the length of the elements present within.
Examples:

```Input : list = ["rohan", "amy", "sapna", "muhammad",
"aakash", "raunak", "chinmoy"]
Output : ['amy', 'rohan', 'sapna', 'aakash', 'raunak',

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 of performing this. Anyone can use there own algorithmic technique, but Python provides us with various built-in functions to perform these. The built-in functions include sort() and sorted() along with the key parameter. We can perform these in two ways. One way is to sort the list by creating a new list and another way is to sort within the given list, saving space.

The syntax for sorting by creating a new list is:

`sorted_list = sorted(unsorted_list, key=len)`
 `# Python code to sort a list by creating ` `# another list Use of sorted()` `def` `Sorting(lst):` `    ``lst2 ``=` `sorted``(lst, key``=``len``)` `    ``return` `lst2` `     ` `# Driver code` `lst ``=` `[``"rohan"``, ``"amy"``, ``"sapna"``, ``"muhammad"``, ` `       ``"aakash"``, ``"raunak"``, ``"chinmoy"``]` `print``(Sorting(lst))`

The syntax for sorting without creating a new list is:

`unsorted_list.sort(key=len)`
 `# Python code to sort a list without ` `# creating another list Use of 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']
```

Working:
These key function of Python’s while sorting implemented is known as the decorate-sort-undecorate design pattern. It follows the following steps:

1. Each element of the list is temporarily replaced with a “decorated” version that includes the result of the key function applied to the element.
2. The list is sorted based upon the natural order of the keys.
3. The decorated elements are replaced by the original elements.

The code for sorting by creating a new dummy list is:

 `import` `numpy` ` ` `def` `Sorting(lst):` ` ` `    ``# list for storing the length of each string in list ` `    ``lenlist``=``[]   ` `    ``for` `x ``in` `lst:` `         ``lenlist.append(``len``(x))     ` ` ` `    ``# return a list with the index of the sorted` `    ``# items in the list` `    ``sortedindex ``=` `numpy.argsort(lenlist)  ` ` ` `    ``# creating a dummy list where we will place the ` `    ``# word according to the sortedindex list ` `    ``lst2 ``=` `[``'dummy'``]``*``len``(lst)   ` ` ` `    ``# print(sortedindex,lenlist)` `    ``for` `i ``in` `range``(``len``(lst)):    ` ` ` `        ``# placing element in the lst2 list by taking the` `        ``# value from original list lst where it should belong ` `        ``# in the sorted list by taking its index from sortedindex` `        ``lst2[i] ``=` `lst[sortedindex[i]]     ` `                                         ` `    ``return` `lst2` `     ` `# Driver code` `lst ``=` `[``"rohan"``, ``"amy"``, ``"sapna"``, ``"muhammad"``, ` `       ``"aakash"``, ``"raunak"``, ``"chinmoy"``]` `print``(Sorting(lst))`

Output:

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

Last Updated on November 13, 2021 by admin

## Python – Unzip a list of tuplesPython – Unzip a list of tuples

Python | Unzip a list of tuples The zipping techniques, that is assigning a key-value

## Python – Create list of numbers with given rangePython – Create list of numbers with given range

Python | Create list of numbers with given range Given two numbers r1 and r2

## Take input from stdin in PythonTake input from stdin in Python

Take input from stdin in Python The sys module in python helps us to access the variables

## Python String splitlines() MethodPython String splitlines() Method

Python String splitlines() Method Python String splitlines() method is used to split the lines at line boundaries.

## Python 3 – input() functionPython 3 – input() function

Python 3 – input() function In Python, we use input() function to take input from the user.

## Python – geometry method in TkinterPython – geometry method in Tkinter

Python | geometry method in Tkinter Tkinter is a Python module that is used to develop

## Python program to print all odd numbers in a rangePython program to print all odd numbers in a range

Given starting and end points, write a Python program to print all odd numbers in

## Extract text from PDF File using PythonExtract text from PDF File using Python

Extract text from PDF File using Python All of you must be familiar with what