Skip to content
Related Articles

Related Articles

Python | Sort all sublists in given list of strings
  • Last Updated : 28 Feb, 2019

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




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



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

 
Method #2 : Using lambda and sorted




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

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

 
Method #3 : Using iteration and sort




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

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

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :