Open In App

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

Last Updated : 08 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# 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))


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




# 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.

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):
 
    # 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']

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.



Previous Article
Next Article

Similar Reads

Python | Sort list according to other list order
Sorting is an essential utility used in majority of programming, be it for competitive programming or development. Conventional sorting has been dealt earlier many times. This particular article deals with sorting with respect to some other list elements. Let's discuss certain ways to sort list according to other list order. Method #1 : Using List
5 min read
Python | Sort a list according to the second element in sublist
In this article, we will learn how to sort any list, according to the second element of the sublist present within the main list. We will see two methods of doing this. We will learn three methods of performing this sort. One by the use of Bubble Sort, the second by using the sort() method, and last but not the least by the use of the sorted() meth
9 min read
Python Program to Sort the list according to the column using lambda
Given a list, the task is to sort the list according to the column using the lambda approach. Examples: Input : array = [[1, 3, 3], [2, 1, 2], [3, 2, 1]] Output : Sorted array specific to column 0, [[1, 3, 3], [2, 1, 2], [3, 2, 1]] Sorted array specific to column 1, [[2, 1, 2], [3, 2, 1], [1, 3, 3]] Sorted array specific to column 2, [[3, 2, 1], [2
2 min read
Python - Sort list of Single Item dictionaries according to custom ordering
Given single item dictionaries list and keys ordering list, perform sort of dictionary according to custom keys. Input : test_list1 = [{'is' : 4}, {"Gfg" : 10}, {"Best" : 1}], test_list2 = ["Gfg", "is", "Best"] Output : [{'Gfg': 10}, {'is': 4}, {'Best': 1}] Explanation : By list ordering, dictionaries list get sorted. Input : test_list1 = [{"Gfg" :
4 min read
Sort an array according to the increasing frequency of the digit K in the array elements
Given an array arr[] of size N, and an integer K representing a digit, the task is to print the given array in increasing order according to the increasing frequency of the digit K in the array elements. Examples: Input: arr[] = {15, 66, 26, 91}, K = 6Output: 15 91 26 66Explanation:The frequency of digit 6 in array elements is {0, 2, 1, 0}. The ele
8 min read
Python | Sort an array according to absolute difference
Given an array of N distinct elements and a number val, rearrange the array elements according to the absolute difference with val, i. e., element having minimum difference comes first and so on. Also the order of array elements should be maintained in case two or more elements have equal differences. Examples: Input: val = 6, a = [7, 12, 2, 4, 8,
3 min read
Python Program to Sort Matrix Rows According to Primary and Secondary Indices
Given Matrix, the task here is to write a Python program to sort rows based on primary and secondary indices. First using primary indices the rows will be arranged based on the element each row has at the specified primary index. Now if two rows have the same element at the given primary index, sorting will be performed again using secondary index.
3 min read
Python | Reshape a list according to given multi list
Given two lists, a single dimensional and a multidimensional list, write Python program to reshape the single dimensional list according to the length of multidimensional list. Examples: Input : list1 = [[1], [2, 3], [4, 5, 6]] list2 = ['a', 'b', 'c', 'd', 'e', 'f'] Output : [['a'], ['b', 'c'], ['d', 'e', 'f']] Input : list1 = [[8, 2, 5], [1], [12,
7 min read
Tag sort or Bucket sort or Bin sort in Python
Tag sort, also known as Bucket sort or Bin sort, is a non-comparison based sorting algorithm that distributes elements of an array into a number of "buckets", and then sorts each bucket individually. Tag sort or Bucket sort or Bin sort Algorithm:Determine Range:Find the maximum and minimum values in the input array to determine the range of tags ne
2 min read
Sort an array according to the increasing count of distinct Prime Factors
Given an array of integers. The task is to sort the given array on the basis of increasing count of distinct prime factors. Examples: Input : arr[] = {30, 2, 1024, 210, 3, 6} Output : 2 1024 3 6 30 210 Input : arr[] = {12, 16, 27, 6} Output : 16 27 6 12 A naive approach is to find all the prime factors of each elements of the array and pair the cou
9 min read
Practice Tags :
three90RightbarBannerImg