Skip to content
Related Articles

Related Articles

Python | Sort list of lists by the size of sublists

View Discussion
Improve Article
Save Article
  • Last Updated : 05 Apr, 2022
View Discussion
Improve Article
Save Article

Given a list of lists, the task is to sort a list on the basis of size of sublists. Let’s discuss a few methods to do the same. Method #1: Using sort 

Python3




# Python code to demonstrate
# sort list of list
# on the basis of size of sublist
 
ini_list = [[1, 2, 3], [1, 2], [1, 2, 3, 4],
                [1, 2, 3, 4, 5], [2, 4, 6]]
 
# printing initial ini_list
print ("initial list", str(ini_list))
 
# sorting on basis of size of list
ini_list.sort(key = len)
 
# printing final result
print("final list", str(ini_list))


Output:initial list [[1, 2, 3], [1, 2], [1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 4, 6]] final list [[1, 2], [1, 2, 3], [2, 4, 6], [1, 2, 3, 4], [1, 2, 3, 4, 5]]

  Method #2: Using lambda 

Python3




# Python code to demonstrate
# sort list of list
# on the basis of size of sublist
 
ini_list = [[1, 2, 3], [1, 2], [1, 2, 3, 4],
                [1, 2, 3, 4, 5], [2, 4, 6]]
 
# printing initial ini_list
print ("initial list", str(ini_list))
 
# sorting on basis of size of list
ini_list.sort(key = lambda x:len(x))
 
# printing final result
print("final list", str(ini_list))


Output:initial list [[1, 2, 3], [1, 2], [1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 4, 6]] final list [[1, 2], [1, 2, 3], [2, 4, 6], [1, 2, 3, 4], [1, 2, 3, 4, 5]]

  Method #3: Using sorted 

Python3




# Python code to demonstrate
# sort list of list
# on the basis of size of sublist
 
ini_list = [[1, 2, 3], [1, 2], [1, 2, 3, 4],
                [1, 2, 3, 4, 5], [2, 4, 6]]
 
# printing initial ini_list
print ("initial list", str(ini_list))
 
# sorting on basis of size of list
result = sorted(ini_list, key = len)
 
# printing final result
print("final list", str(result))


Output:initial list [[1, 2, 3], [1, 2], [1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 4, 6]] final list [[1, 2], [1, 2, 3], [2, 4, 6], [1, 2, 3, 4], [1, 2, 3, 4, 5]]

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!