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

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code  to sort all sublists 
# in given list of strings
  
# List initialization
Input = [['Machine', 'London', 'Canada', 'France', 'Lanka'],
         ['Spain', 'Munich'],
         ['Australia', 'Mandi']]
  
# Using map for sorting
Output = list(map(sorted, Input))
  
# Printing output
print(Output)

chevron_right


Output:

[[‘Canada’, ‘France’, ‘Lanka’, ‘London’, ‘Machine’], [‘Munich’, ‘Spain’], [‘Australia’, ‘Mandi’]]

 
Method #2 : Using lambda and sorted

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code  to sort all sublists
# in given list of strings
  
# List initialization
Input = [['Machine', 'London', 'Canada', 'France', 'Lanka'],
         ['Spain', 'Munich'],
         ['Australia', 'Mandi']]
  
# using lambda and sorted
Output = [sorted(x, key = lambda x:x[0]) for x in Input]
  
# Printing output
print(Output)

chevron_right


Output:

[[‘Canada’, ‘France’, ‘London’, ‘Lanka’, ‘Machine’], [‘Munich’, ‘Spain’], [‘Australia’, ‘Mandi’]]

 
Method #3 : Using iteration and sort

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code  to sort all sublists
# in given list of strings
  
# List initialization
Input = [['Machine', 'London', 'Canada', 'France', 'Lanka'],
         ['Spain', 'Munich'],
         ['Australia', 'Mandi']]
  
# sorting sublist
for sublist in Input:
    sublist.sort()
  
# Printing output
print(Input)

chevron_right


Output:

[[‘Canada’, ‘France’, ‘Lanka’, ‘London’, ‘Machine’], [‘Munich’, ‘Spain’], [‘Australia’, ‘Mandi’]]



My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.