Python | Sort all sublists in given list of strings
Given a list of lists, the task is to sort each sublist in the given list of strings.
Example:
Input:
lst = [['Machine', 'London', 'Canada', 'France'],
['Spain', 'Munich'],
['Australia', 'Mandi']]
Output:
flist = [['Canada', 'France', 'London', 'Machine'],
['Munich', 'Spain'],
['Australia', 'Mandi']]
There are multiple ways to sort each list in alphabetical order.
Method #1 : Using map
Python3
Input = [[ 'Machine' , 'London' , 'Canada' , 'France' , 'Lanka' ],
[ 'Spain' , 'Munich' ],
[ 'Australia' , 'Mandi' ]]
Output = list ( map ( sorted , Input ))
print (Output)
|
Output:
[[‘Canada’, ‘France’, ‘Lanka’, ‘London’, ‘Machine’], [‘Munich’, ‘Spain’], [‘Australia’, ‘Mandi’]]
Time Complexity: O(n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_list”.
Method #2 : Using lambda and sorted
Python3
Input = [[ 'Machine' , 'London' , 'Canada' , 'France' , 'Lanka' ],
[ 'Spain' , 'Munich' ],
[ 'Australia' , 'Mandi' ]]
Output = [ sorted (x, key = lambda x:x[ 0 ]) for x in Input ]
print (Output)
|
Output:
[[‘Canada’, ‘France’, ‘London’, ‘Lanka’, ‘Machine’], [‘Munich’, ‘Spain’], [‘Australia’, ‘Mandi’]]
Time Complexity: O(nlogn)
Auxiliary Space: O(1)
Method #3 : Using iteration and sort
Python3
Input = [[ 'Machine' , 'London' , 'Canada' , 'France' , 'Lanka' ],
[ 'Spain' , 'Munich' ],
[ 'Australia' , 'Mandi' ]]
for sublist in Input :
sublist.sort()
print ( Input )
|
Output:
[[‘Canada’, ‘France’, ‘Lanka’, ‘London’, ‘Machine’], [‘Munich’, ‘Spain’], [‘Australia’, ‘Mandi’]]
Method #4 : Using simple list comprehension
Another approach to sort the sublists in a list of strings is to use the built-in sorted function and a list comprehension. This method involves iterating over each sublist in the list and sorting it using the sorted function, then returning the sorted sublist in a new list using a list comprehension. Here is an example of how this can be done:
Python3
lst = [[ 'Machine' , 'London' , 'Canada' , 'France' , 'Lanka' ],
[ 'Spain' , 'Munich' ],
[ 'Australia' , 'Mandi' ]]
sorted_lst = [ sorted (sublist) for sublist in lst]
print (sorted_lst)
|
Output
[['Canada', 'France', 'Lanka', 'London', 'Machine'], ['Munich', 'Spain'], ['Australia', 'Mandi']]
The time complexity of this approach is O(nlog(n)), where n is the total number of elements in the list, because the sorted function uses a sorting algorithm with a time complexity of O(nlog(n)). The auxiliary space is O(n) because a new list is created to hold the sorted sublists.
Last Updated :
17 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...