In this program, we need to accept a list and sort it based on the length of the elements present within.
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 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)
The syntax for sorting without creating a new list is:
['amy', 'rohan', 'sapna', 'aakash', 'raunak', 'chinmoy', 'muhammad']
These key function of Python’s while sorting implemented is known as the decorate-sort-undecorate design pattern. It follows the following steps:
- Each element of the list is temporarily replaced with a “decorated” version that includes the result of the key function applied to the element.
- The list is sorted based upon the natural order of the keys.
- The decorated elements are replaced by the original elements.
- Python | Sort dictionary by value list length
- Python | Sort list of lists by lexicographic value and then length
- Python | Sort list elements by frequency
- Python List Comprehension | Sort even-placed elements in increasing and odd-placed in decreasing order
- Python | Find maximum length sub-list in a nested list
- Python | Convert 1D list to 2D list of variable length
- Python | Sort Flatten list of list
- Python | Sort the values of first list using second list
- Python | Sort list of list by specified index
- Python | Sort list according to other list order
- Sort the linked list in the order of elements appearing in the array
- Python list sort()
- Python | Add list elements with a multi-list based on index
- Python | Replace elements in second list with index of same element in first list
- Python | Sorting list of lists with similar list elements
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.