Python | Sort a List according to the Length of the Elements
Last Updated :
08 May, 2023
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',
'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 their
length.
There are many ways of performing this. Anyone can use their 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)
Python3
def Sorting(lst):
lst2 = sorted (lst, key = len )
return lst2
lst = ["rohan", "amy", "sapna", "muhammad",
"aakash", "raunak", "chinmoy"]
print (Sorting(lst))
|
Time complexity: O(n*logn), as sorted() function is used.
Auxiliary Space: O(n), where n is length of lst list.
The syntax for sorting without creating a new list is:
unsorted_list.sort(key=len)
Python3
def Sorting(lst):
lst.sort(key = len )
return lst
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:
- 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.
Time Complexity: O(n log n)
Auxiliary Space: O(1)
The code for sorting by creating a new dummy list is:
Python3
import numpy
def Sorting(lst):
lenlist = []
for x in lst:
lenlist.append( len (x))
sortedindex = numpy.argsort(lenlist)
lst2 = [ 'dummy' ] * len (lst)
for i in range ( len (lst)):
lst2[i] = lst[sortedindex[i]]
return lst2
lst = ["rohan", "amy", "sapna", "muhammad",
"aakash", "raunak", "chinmoy"]
print (Sorting(lst))
|
Output:
['amy', 'rohan', 'sapna', 'aakash', 'raunak', 'chinmoy', 'muhammad']
Reference: stackoverflow
Method: Using lambda function and sorted() function
This approach uses sorted() function along with a lambda function as the key parameter to sort the list based on the length of the elements present within. Below is the algorithm
Algorithm:
Create a list with the elements to.
UsING the sorted() function with a lambda function as the key parameter sort the list based on the length of its elements.
The lambda function takes an element x and returns the length of that element len(x).
The sorted() function returns a new sorted list.
Print the sorted list.
Python3
myList = [ "rohan" , "amy" , "sapna" , "muhammad" , "aakash" , "raunak" , "chinmoy" ]
sortedList = sorted (myList, key = lambda x: len (x))
print (sortedList)
|
Output
['amy', 'rohan', 'sapna', 'aakash', 'raunak', 'chinmoy', 'muhammad']
Time Complexity: O(n log n)
The sorted() function has a time complexity of O(n log n) for the average and worst-case scenarios, where n is the number of elements in the list.
Space Complexity: O(n)
The auxiliary space of this method is O(n) because a new sorted list is created with n elements.
Please Login to comment...