Javatpoint Logo
Javatpoint Logo

Sort a List by the Lengths of its Elements in Python

The goal is to sort the list based on the length of the elements. Also, assuming that the list contains only one type of element.

For example:

Explanation: The input list is a list of strings: ["Javatpoint", "Google", "Yahoo", "Microsoft"]. We can see that the lengths of these strings are 10, 6, 5, and 9, respectively. So, the sorted list based on the length of the elements would be ["Yahoo", "Google", "Microsoft", "Javatpoint"] because "Yahoo" has the shortest length (5), followed by "Google" (6), then "Microsoft" (9), and finally "Javatpoint" (10).

Explanation: The input list is a list of lists of strings: [["Arun", "Rohan", "Vikesh"], ["Java", "Python"], ["Kavi"], ["Suraj", "Kiran"]]. Here, we need to sort the list based on the length of the sub-lists. The length of each sub-list is 3, 2, 1, and 2, respectively. Therefore, the sorted list would be [["Kavi"], ["Java", "Python"], ["Suraj", "Kiran"], ["Arun", "Rohan", "Vikesh"]].

NOTE: In the case of a tie, where two or more elements have the same length, the element that appears first in the input list should come first in the output list. For example, in the second example, the sub-lists ["Suraj", ["Kiran"]] and ["Arun", "Rohan", "Vikesh"] both have a length of 2, but ["Suraj", ["Kiran"]] appears before ["Arun", "Rohan", "Vikesh"] in the input list, so it comes before it in the output list.

There are various methods to sort a Python list by the length of the elements. One can use their own algorithm to sort the list. In Python, we have inbuilt functions such as sort() and sorted() with a key parameter which we can use to sort the list based on the length of the elements.

Method 1 - Using sort() function

In this method, we will use the sort function to sort the list, and the key parameter will be 'len' function.

CODE:

Output:

Input list 1 = ['Javatpoint', 'Google', 'Yahoo', 'Microsoft']
Input list 2 = [['Arun', 'Rohan', 'Vikesh'], ['Java', 'Python'], ['Kavi'], ['Suraj', 'Kiran']]

Sorted list 1 = ['Yahoo', 'Google', 'Microsoft', 'Javatpoint']
Sorted list 2 = [['Kavi'], ['Java', 'Python'], ['Suraj', 'Kiran'], ['Arun', 'Rohan', 'Vikesh']]

Explanation:

In the above program, we have first declared two lists: a list of strings and a list of sub-lists. Then we used the sort function to sort the lists and passed the len function as the key argument.

For each element in the list, the len function returns its length, and the lists are sorted based on the length of the elements. Finally, we printed the sorted list.

Time Complexity = O(n): The sorted algorithm used has the worst time complexity of O(n logn).

Space Complexity = O(1): No extra space is needed. The lists are sorted within themselves.

Method 2 - Using Sorted() Function

In this method, we will use the sorted function to sort the list. The first argument of the sorted function will be the list itself, and the key parameter will be the len function.

CODE:

Output:

Input list 1 = ['Javatpoint', 'Google', 'Yahoo', 'Microsoft']
Input list 2 = [['Arun', 'Rohan', 'Vikesh'], ['Java', 'Python'], ['Kavi'], ['Suraj', 'Kiran']]

Sorted list 1 = ['Yahoo', 'Google', 'Microsoft', 'Javatpoint']
Sorted list 2 = [['Kavi'], ['Java', 'Python'], ['Suraj', 'Kiran'], ['Arun', 'Rohan', 'Vikesh']]

Explanation:

In the above program, we have declared two lists: a list of strings and a list of sub-lists. Then we used the sorted() function to sort the lists.

The first argument of the sorted function is the list to be sorted, and the key parameter is the len function.

For each element in the list, the len function returns its length, and the list is sorted by the lengths of the elements.

The only difference between method 1 and method 2 is that in method 1, the lists are sorted within themselves. In method 2, new sorted lists are created, and the original lists are unaffected.

Time complexity = O(n): The sorted algorithm used has the worst time complexity of O(n logn).

Space Complexity =O(n): Extra space is needed to store the sorted list. The size of the sorted list depends on the length of the input list, making the space complexity equal to O(n).

Method 3 - Using numpy() library

In this method, we will use the numpy library and argsort method to sort the list based on the lengths of the elements.

CODE:

Output:

Input list = ['Javatpoint', 'Google', 'Yahoo', 'Microsoft']

Sorted list = ['Yahoo', 'Google', 'Microsoft', 'Javatpoint']

Explanation:

First, we import the numpy library with the alias np. We convert the list to a numpy array using the np.array() function and store the result in my_array. Then we sort the array based on the length of its elements using np.argsort(), which returns the indices that would sort the array. We have passed list(map(len, my_array)) as the sorting key, which returns a list of the lengths of the strings in the array.

We then apply the sorting indices to the original array using slicing syntax (my_array[indices]) and store the result in sorted_array. We finally convert the sorted array back to a list using the list() constructor and store it in sorted_list.

Finally, we print the result into the console.

Time complexity = O(n logn): The np.argsort() function has the worst case time complexity of O(n logn), and the time complexity of list(map(len, my_array) operation is O(n), as it only iterates over the elements of the array once to count the lengths of its elements.

Space Complexity = O(n): We have created a numpy array of size n. Also, the list(map(len, my_array) creates a list of size n, making the space complexity of the program equal to O(n).

NOTE: In this method, we have used the numpy library and converted the list into a numpy array which is not an efficient method to sort the list. We can simply use the in-builts sort() function to sort the list and pass the len function as the key parameter, as shown in the previous method.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA