Python | Sort list of lists by the size of sublists

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 bais of size of list
ini_list.sort(key = len)
  
# printing final result
print("final list", str(ini_list))

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 bais of size of list
ini_list.sort(key = lambda x:len(x))
  
# printing final result
print("final list", str(ini_list))

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 bais of size of list
result = sorted(ini_list, key = len)
  
# printing final result
print("final list", str(result))

chevron_right


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

Check out this Author's contributed articles.

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.