Python | Sort Flatten list of list

The flattening of list of lists has been discussed earlier, but sometimes, in addition to flattening, it is also required to get the string in a sorted manner. Let’s discuss certain ways in which this can be done.

Method #1 : Using sorted() + list comprehension
This idea is similar to flattening a list of list but in addition to it, we add a sorted function to sort the returned flattened list done by list comprehension.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# sort flatten list of list 
# using sorted + list comprehension
  
# initializing list of list 
test_list = [[3, 5], [7, 3, 9], [1, 12]]
  
# printing original list of list 
print("The original list : " + str(test_list))
  
# using sorted + list comprehension
# sort flatten list of list
res = sorted([j for i in test_list for j in i])
  
# print result
print("The sorted and flattened list : " + str(res))

chevron_right


Output :

The original list : [[3, 5], [7, 3, 9], [1, 12]]
The sorted and flattened list : [1, 3, 3, 5, 7, 9, 12]

 

Method #2 : Using itertools.chain() + sorted()
The task that was done by list comprehension above can also be performed using the chain function that links elements of list and then sorted function does the task of sorting.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# sort flatten list of list 
# using itertools.chain() + sorted()
from itertools import chain
  
# initializing list of list 
test_list = [[3, 5], [7, 3, 9], [1, 12]]
  
# printing original list of list 
print("The original list : " + str(test_list))
  
# using itertools.chain() + sorted()
# sort flatten list of list
res = sorted(chain(*test_list))
  
# print result
print("The sorted and flattened list : " + str(res))

chevron_right


Output :

The original list : [[3, 5], [7, 3, 9], [1, 12]]
The sorted and flattened list : [1, 3, 3, 5, 7, 9, 12]


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.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.